2012-11-05 23 views
6

Jest coś, czego nie dostaję w TypeScript, jeśli chodzi o pliki deklaracji i biblioteki stron trzecich napisane w czystym JavaScript. Powiedzmy, że mam następujące klasy javascript:Jak używać plików deklaracji w TypeScript

$ cat SomeClass.js 

var SomeClass = (function() { 
    function SomeClass() { 
    } 
    SomeClass.prototype.method1 = function() { 
      return "some string"; 
    }; 
    return SomeClass; 
})(); 
exports.SomeClass = SomeClass; 

I chcę, aby uzyskać typ sprawdzania, więc tworzę plik zgłoszenia takiego:

$ cat test.d.ts 

class SomeClass { 
    public method1(): string; 
} 

Następnie chcę użyć klasy i deklaracji złożyć w pewnym kodzie:

$ cat main.ts 

///<reference path="./test.d.ts"/> 
import ns = module("./SomeClass"); 

function test(): string { 
    var sc = new ns.SomeClass(); 
    return sc.method1(); 
} 

Gdy próbuję go skompilować, otrzymuję to:

$ tsc main.ts 
main.ts(2,19): The name '"./SomeClass"' does not exist in the current scope 
main.ts(2,19): A module cannot be aliased to a non-module type 
main.ts(5,16): Expected var, class, interface, or module 

Z tego, co wiem, instrukcja importu wymaga istnienia rzeczywistej klasy TypeScript, a instrukcja referencyjna nie jest wystarczająca, aby pomóc kompilatorowi dowiedzieć się, jak sobie z nim poradzić.

Próbowałem zmieniając go do

import ns = module("./test.d"); 

ale bez kości albo.

Jedyny sposób mogę uzyskać to faktycznie kompilacji i prowadzony jest skorzystanie z komunikatu żądania zamiast importu, tak:

$ cat main.ts 

///<reference path="./node.d.ts"/> 
///<reference path="./test.d.ts"/> 
var ns = require("./SomeClass"); 

function test(): string { 
    var sc = new ns.SomeClass(); 
    return sc.method1(); 
} 

Problem z tym kodem jest, że maszynopis nie jest uruchomiona żadna kontrola typów . W rzeczywistości mogę całkowicie usunąć linię

Jednakże, jeśli usunę żądanie, mogę uzyskać sprawdzenie typu, ale kod rozkręci się w czasie wykonywania, ponieważ nie ma instrukcji wymagającej.

$ cat main.ts 

///<reference path="./test.d.ts"/> 

function test(): string { 
    var sc = new SomeClass(); 
    return sc.method1(); 
} 

test(); 

$ node main.js 

main.js:2 
    var sc = new SomeClass(); 
       ^
ReferenceError: SomeClass is not defined 
    ... 

Odpowiedz

7

kot test.d.ts

declare module "SomeClass.js" { 
    class SomeClass { 
     method1(): string; 
    } 
} 

kot Main.ts

///<reference path="test.d.ts"/> 
import ns = module("SomeClass.js"); 

function test() { 
    var sc = new ns.SomeClass(); 
    return sc.method1(); 
} 

TSC Main.ts --declarations

kot Main.js

var ns = require("SomeClass.js") 
function test() { 
    var sc = new ns.SomeClass(); 
    return sc.method1(); 
} 

kot Main.d.ts

import ns = module ("SomeClass.js"); 
function test(): string; 
Powiązane problemy