typescript,如何在类定义之外添加方法
我尝试在原型上添加它,但错误
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')
}
答案 0 :(得分:5)
它抱怨是因为你没有定义B
有方法say
你可以:
class B {
name: string = 'sam.sha'
say: () => void;
}
B.prototype.say = function(){
console.log('define method in prototype')
}
或者:
class B {
name: string = 'sam.sha'
}
interface B {
say(): void;
}
B.prototype.say = function(){
console.log('define method in prototype')
}