typescript ,如何在类定义之外添加方法
我尝试在原型(prototype)上添加它,但是出错
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')
}
最佳答案
它提示是因为你没有定义 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')
}
关于javascript - TypeScript - 如何在类定义之外添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38432673/