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')
}
Yes you can definitely have functions outside of a class.
No its not possible. In java everything (objects) belongs to some class. So we can not declare function(method) outside a class.
Edit You can have public methods in non-public classes, but you probably don't want that since the non-public classes will have limited (perhaps none) visibility outside of the declaring class.
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')
}
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