Skip to content

Instantly share code, notes, and snippets.

@xperiments
Created June 20, 2013 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xperiments/5826814 to your computer and use it in GitHub Desktop.
Save xperiments/5826814 to your computer and use it in GitHub Desktop.
Typescript Newable Types
http://stackoverflow.com/questions/13407036/how-does-typescript-interfaces-with-construct-signatures-work
Construct signatures in interfaces are not implementable in classes; they're only for defining existing JS APIs that define a 'new'-able function. Here's an example involving interfaces new signatures that does work:
interface ComesFromString {
name: string;
}
interface StringConstructable {
new(n: string): ComesFromString;
}
class MadeFromString implements ComesFromString {
constructor (public name: string) {
console.log('ctor invoked');
}
}
function makeObj(n: StringConstructable) {
return new n('hello!');
}
console.log(makeObj(MadeFromString).name);
This creates an actual constraint for what you can invoke makeObj with:
class Other implements ComesFromString {
constructor (public name: string, count: number) {
}
}
makeObj(Other); // Error! Other's constructor doesn't match StringConstructable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment