Adam Hoffman Adam Hoffman - 18 days ago 5
Javascript Question

Typescript and sql.js - how to tell Typescript it's there

I might be approaching this completely incorrectly, so any advice is appreciated. I'm currently trying to dig in deep to Typescript, and have decided to simultaneously use Sql.js (the JS version of SQLite) at the same time...

My first instinct to use Sql.js was to search for a .d.ts set of bindings around Sql.js so that I could easily start using it with TS. I've come up with no bindings so far (I don't think one exists yet), but figured I could just start "define"-ing in the stuff that I need from the library...

Starting with one of the simple examples from the "sql.js" docs, you have something like this:

var sql = window.SQL;
var db = new sql.Database();


Moving to the typescript side, I wanted to let TS know that after the sql.js library is included, the window object now has a property called SQL, which is essentially the hook to the rest of the library. I figured I needed to do this because, of course, when I type "window." (window-dot) in Visual Studio in my TS file, the Intellisense presented doesn't know about the SQL property now hanging off of "window". So... I dug around Stack, and concluded that I could solve this with a "declare" which I basically see as a way to tell TS just enough about the libraries that I don't have binding files for (.d.ts files).

However, in doing this, I can't seem to construct the syntax for such a declaration. I've tried:

declare var window.SQL : any;
declare var window.SQL;
declare var SQL = window.SQL;
declare window.SQL;


None of these work, of course.

So, the question is, how can I let TS know about new properties introduced by JS libraries on standard objects like "window", and the follow up question is, of course, is this even the right way to be approaching this?

Thanks for any insight.

Answer

window is declared to be of type interface Window (in lib.d.ts). So you need to add to that if you want to use window.SQL :

interface Window{
    SQL:any;
}

var sql = window.SQL;
var db = new sql.Database();

Recommend:

Personally I would recommend not using it off of window and just do

declare var SQL:any;
var db = new SQL.Database();

By default the variable access in the browser is on window.

Comments