Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

It seems like it would be very useful in TypeScript to require that a module implement an interface. Is there any particular reason why they've chosen to not implement this ability?

I can't think of any reason why it would be undesirable to allow a module implement an interface, but if it is, then is there any other way to require a module provide a certain set of properties / methods?

like image 956
Allen Rice Avatar asked Apr 18 '13 00:04

Allen Rice


People also ask

Can interface implement interface TypeScript?

An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.

Can we export interface in TypeScript?

Use a named export to export an interface in TypeScript, e.g. export interface Person{} . The exported interface can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file.

What does ?: Mean in TypeScript?

Using ?: with undefined as type definition While there are no errors with this interface definition, it is inferred the property value could undefined without explicitly defining the property type as undefined . In case the middleName property doesn't get a value, by default, its value will be undefined .


1 Answers

You can force a compile error if a module doesn't adhere to an interface like this (technically non-zero runtime overhead, but unlikely to actually matter):

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

As for why can't you say module mod implements foo? All features start at minus 100.

Edit to add -- here are some other (somewhat wacky) things you could write in lieu of the var statement above if you wanted to avoid creating a new top-level var:

<foo>mod; // Shortest, probably fastest?
<foo>undefined === mod; // Clearest non-var version?
like image 71
Ryan Cavanaugh Avatar answered Oct 13 '22 12:10

Ryan Cavanaugh