Created
June 20, 2013 21:28
-
-
Save xperiments/5826814 to your computer and use it in GitHub Desktop.
Typescript Newable Types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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