gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:57 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com