繁体   English   中英

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

[英]TypeScript - How to add a method outside the class definition

打字稿,如何在类定义之外添加方法

我尝试将其添加到原型上,但是出错

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM