类型文字属性在 TS 中不能有初始化器
A type literal property cannot have an initializer in TS
尝试在键入对象时提供值时出现错误“类型文字属性不能具有初始值设定项”。
要解决该错误,请将您的类型与类属性或对象定义中的默认值分开。
下面是错误如何发生的示例。
索引.ts
export class Employee { address: { // ⛔️ Error: A type literal property cannot have an initializer.ts(1247) country: string = 'Germany'; city: string; }; }
我们试图为该address.country
属性提供一个值,但我们不允许混合类型和值声明。
先声明类型然后设置默认值
要解决该错误,您首先声明类型,然后设置默认值。
索引.ts
type Address = { country: string; city: string; }; export class Employee { address: Address = { country: 'Chile', city: 'Santiago', }; }
该示例使用类型别名来设置对象中的country
和属性的类型。city
address
为基本类型定义类属性
在为基本类型定义类属性时,您可以使用以下方法。
索引.ts
export class Employee { // ✅ this is valid country: string = 'Germany'; getCountry() { return this.country; } } const emp = new Employee(); console.log(emp.country); // 👉️ "Germany"
您可以用相同的方式在类的构造函数中设置参数的类型和默认值。
这是一个示例构造函数,它接受一个对象并使用默认值。
索引.ts
type Address = { country: string; city: string; }; export class Employee { constructor( public address: Address = { country: 'Chile', city: 'Santiago', }, ) { this.address = address; } getAddress() { return { country: this.address.country, city: this.address.city, }; } } const emp = new Employee({ country: 'Brazil', city: 'São Paulo' }); // 👇️ {country: 'Brazil', city: 'São Paulo'} console.log(emp.getAddress());
请注意,我们总是在冒号之后声明类型,并可选择在等号之后提供默认值。
这里是一个构造函数的例子,它定义了它的参数的类型和默认值。
索引.ts
export class Employee { constructor(public name: string = 'Bobby Hadz', public salary: number = 100) { this.name = name; this.salary = salary; } getData() { return { name: this.name, salary: this.salary, }; } } const emp = new Employee('Jeff', 200); // 👇️ {name: 'Jeff', salary: 200} console.log(emp.getData());
请注意,定义默认值是可选的。
I’ve also written a detailed article on
how to set default values for class properties in TS.
# Additional Resources
You can learn more about the related topics by checking out the following
tutorials:
- Class implementing Interfaces in TypeScript
- A class member cannot have the ‘const’ keyword in TS
- How to declare an Array of Objects in TypeScript
- Setting optional parameters in Functions or Classes in TS
- Create custom Class that extends from Error in TypeScript
- How to initialize a typed Empty Object in TypeScript
- Declare and Type a nested Object in TypeScript
- An index signature parameter type cannot be a literal type or a generic type