为什么VS Code不允许我在TypeScript构造函数中使用'name'作为参数?
问题原因与修复方案
- 核心错误是你的
constructor定义位置错误:你把构造函数写在了Recipe类的闭合花括号}之外,不属于类的成员,才会触发各类不符合预期的报错。
构造函数写在类外部时,this指向全局作用域,全局环境下的name是挂载在顶层对象上的废弃属性,所以会弹出name已废弃的提示;更换参数名后提示找不到标识符,也是因为全局作用域下不存在对应属性的类型定义。 - 次要问题是你没有补全构造函数内所有类属性的赋值逻辑,
description和imagePath两个声明的属性没有完成赋值。
修复后完整代码
export class Recipe { public name: string; public description: string; public imagePath: string; // 构造函数必须定义在类内部 constructor(name: string, desc: string, imagePath: string) { this.name = name; this.description = desc; this.imagePath = imagePath; } }
可选简化写法
TypeScript支持直接在构造函数参数前加修饰符,省略重复的属性声明,代码更精简:
export class Recipe { constructor( public name: string, public description: string, public imagePath: string ) {} }
内容的提问来源于stack exchange,提问作者p4yner56
相关产品推荐
相关产品推荐

