Why can't TypeScript modules implement or stick to an interface? Can I get around this?

It seems like it would be very useful in TypeScript to require a module to implement an interface. Is there any special reason why they decided not to realize this ability?

I can’t think of any reason why it would not be desirable for the module to implement the interface, but if so, is there another way to require the module to provide a certain set of properties / methods?

+5
source share
2 answers

You can force compilation if the module does not adhere to such an interface (technically non-zero overhead at runtime, but this hardly matters):

interface foo {
    bar(): number;
}

module mod {
    export function bar(): number {
        return 0;
    }
}
var mod_is_foo: foo = mod; // errors if you change 'number' to 'string' above

module mod implements foo? 100.

- ( ) , var , var:

<foo>mod; // Shortest, probably fastest?
<foo>undefined === mod; // Clearest non-var version?
+4

Typescript, . , , .

, , , (, ). , var, .

, , , :

var x:foo; 

var x implements foo;

,

var y:foo = mod;

.

:

interface foo {
    bar(): number;
}

module mod {
    export function bar(): number {
        return 0;
    }
}

var x: foo; 
x = mod;

// Still a bit whacky but allowed as module is a type as well as an instance
var y:mod;
y = x;
+1

All Articles