I'm trying to prototype-based programming with typescirpt and found that typescript has limited support for this. So I want to know if using typescript basically gives up the prototype-based programming paradigm?
Here is my demo code:
const Foo = {
init (name: string) {
this.name = name
return this
},
getName(): string {
return this.name
}
}
const Bar = {
init (name: string, label: string) {
Foo.init.call(this, name)
this.label = label
return this
},
getLabel() {
return this.label
}
}
Object.setPrototypeOf(Bar, Foo)
const bar = <typeof Bar> Object.create(Bar)
bar.init('lisiur', 'javascript')
bar.getName()
And in the last line typescript complain that Property 'getName' does not exist on type '{ init(name: string, label: string): any; getLabel(): any; }'.ts(2339). Is there a way to fix it?
update:
In lib.d.ts, Object.create and Object.setPrototypeOf all miss necessary type declaration(they all return any). So is there a way to declare my own create and setPrototypeOf to achieve that?
class? This implements exactly the same thing, but in a much less convenient way.const bar = <typeof Bar & typeof Foo>Object.create(Bar)to solve your issue, but this might not be an issue if you use JavaScript classes as others have mentioned.