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?
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.
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.
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 .
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With