Reputation: 852
typescript, how to add a method outside the class definition
I try to add it on prototype, but error
B.ts
export class B{
name: string = 'sam.sha'
}
//Error:(21, 13) TS2339: Property 'say' does not exist on type 'B'.
B.prototype.say = function(){
console.log('define method in prototype')
}
Upvotes: 6
Views: 2959
Reputation: 164137
It complains because you did not define that B
has the method say
.
You can:
class B {
name: string = 'sam.sha'
say: () => void;
}
B.prototype.say = function(){
console.log('define method in prototype')
}
Or:
class B {
name: string = 'sam.sha'
}
interface B {
say(): void;
}
B.prototype.say = function(){
console.log('define method in prototype')
}
Upvotes: 9