TypeScript类实例调用likePercent方法返回undefined问题求助
问题原因
你当前的写法没有完成MyClass类的真正实例化,仅创建了一个符合MyClass类型结构的普通对象,仅手动赋值了thumbedUp、thumbedDown两个属性,类定义中的likePercent、dislikePercent方法并未被初始化到该对象上,调用时自然返回undefined。
TypeScript为结构类型系统,类型校验仅判断对象结构是否匹配,不会自动为普通对象补全类的成员实现。
修复方案
- 方案1:使用
new关键字实例化类后再赋值属性
const myClass = new MyClass(); myClass.thumbedUp = 10; myClass.thumbedDown = 12; // 调用即可拿到正确结果:myClass.likePercent() 返回 45
- 方案2:为类添加构造函数,实例化时直接传入参数
export class MyClass { thumbedUp?: number; thumbedDown?: number; // 新增构造函数 constructor(thumbedUp: number, thumbedDown: number) { this.thumbedUp = thumbedUp; this.thumbedDown = thumbedDown; } likePercent?= () => Math.round((this.thumbedUp / (this.thumbedDown + this.thumbedUp)) * 100); dislikePercent?= () => Math.round((this.thumbedDown / (this.thumbedDown + this.thumbedUp)) * 100); } // 一步完成实例化与赋值 const myClass = new MyClass(10, 12);
额外优化建议
你当前的类属性均为可选类型,需补充空值、除数为0的边界处理,避免出现NaN报错:
likePercent?= () => { const up = this.thumbedUp ?? 0; const down = this.thumbedDown ?? 0; const total = up + down; return total === 0 ? 0 : Math.round((up / total) * 100); }
内容的提问来源于stack exchange,提问作者Luc
相关产品推荐
相关产品推荐

