TypeScript - 如何在类定义之外添加方法

时间:2016-07-18 09:08:00

标签: javascript typescript ecmascript-6

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')
}

1 个答案:

答案 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')
}