TypeScript类属性异常:playerInformation不存在于Player类型
解决TypeScript中Player类属性不存在的问题
方法1:显式声明类属性并指定类型
TypeScript是强类型语言,类的属性必须提前声明并指定类型。你可以先定义playerInformation属性,同时根据需求指定具体类型(推荐用自定义接口规范结构,也可以用any兼容任意类型):
// 自定义接口规范playerInformation的结构(可选,推荐使用) interface PlayerInfo { name?: string; level?: number; [key: string]: any; // 索引签名支持额外属性 } export default class Player { // 声明属性并指定类型 private playerInformation: PlayerInfo; constructor(playerInformation: PlayerInfo = {}) { console.log("Player initialized"); this.playerInformation = playerInformation; } test() { console.log(this.playerInformation); } }
如果不需要严格类型校验,可简化为:
export default class Player { private playerInformation: any; constructor(playerInformation: any = {}) { console.log("Player initialized"); this.playerInformation = playerInformation; } test() { console.log(this.playerInformation); } }
方法2:使用构造函数参数属性(简洁写法)
TypeScript支持在构造函数参数前添加public/private/protected修饰符,自动将参数转为类属性,无需手动赋值:
interface PlayerInfo { [key: string]: any; } export default class Player { // 参数前加private,自动生成类属性并完成赋值 constructor(private playerInformation: PlayerInfo = {}) { console.log("Player initialized"); } test() { console.log(this.playerInformation); } }
方法3:关闭严格属性初始化检查(不推荐)
若只是临时测试,可在tsconfig.json中修改配置关闭校验,但会弱化TypeScript的类型保障,正式项目不建议使用:
{ "compilerOptions": { "strictPropertyInitialization": false } }
错误原因
你原代码未在Player类中声明playerInformation属性,直接在构造函数中给this赋值,TypeScript无法识别该属性属于Player类的成员,因此抛出属性不存在的错误。
内容的提问来源于stack exchange,提问作者TPGlitch
相关产品推荐
相关产品推荐

