在 TypeScript 中向对象添加属性
How to Add a property to an Object in TypeScript
要在 TypeScript 中向对象添加属性,请在分配给对象的接口上使用问号将该属性设置为可选。然后您可以在以后的某个时间点添加该属性而不会出现类型错误。
// ✅ Add specific property to object interface Person { name: string; age?: number; // 👈️ mark as optional so you can add later } const obj1: Person = { name: 'Tom', }; obj1.age = 30; // ✅ Add any property to object const obj2: Record<string, any> = {}; // 👇️ can now add any property to the object obj2.name = 'Tom'; obj2.age = 30; // ✅ Add any property, but type key-value // pairs you know in advance interface Animal extends Record<string, any> { name: string; age: number; } const obj3: Animal = { name: 'Alfred', age: 3 }; // 👇️ Can now add any property, but name and age are typed obj3.type = 'Dog';
第一个示例展示了如何将接口
age
上的属性设置为optional。Person
age
属性可以是undefined
或. 当您提前知道属性的名称及其值的类型时,可以使用这种方法,因为它可以保证事物的类型安全。 number
现在您可以在没有属性的情况下初始化对象并在以后设置它。
interface Person { name: string; age?: number; // 👈️ mark as optional so you can add later } const obj1: Person = { name: 'Tom', }; obj1.age = 30; // ⛔️ Error: Type '"hello"' is not assignable // to type 'number | undefined'. obj1.age = 'hello';
如果您尝试为该age
属性分配一个非数字值,则会出现错误。
第二个示例使用
Record
实用程序类型 – Record<string, any>
。
// ✅ Add any property to object const obj2: Record<string, any> = {}; // 👇️ can now add any property to the object obj2.name = 'Tom'; obj2.age = 30;
Record
实用程序类型允许我们在 TypeScript 中强制执行对象值的类型,例如type Animal = Record<string, string>
.
Record
键和值是指定的类型。我们为对象any
中的值使用了一种类型,string
为对象中的键使用了一种类型。
这非常广泛,允许我们向any
对象添加任何类型的属性。
The third example shows how to specify the properties and the types in an object
that we know about and use the Record
utility type to allow the user to add
other properties.
// ✅ Add any property, but type key-value // pairs you know in advance interface Animal extends Record<string, any> { name: string; age: number; } const obj3: Animal = { name: 'Alfred', age: 3 }; // 👇️ Can now add any property, but name and age are typed obj3.type = 'Dog';
The interface we created requires the name
and age
properties but also
extends a type that allows any string properties with values of any
type.
This is better than just using the Record
utility type with string
keys and
any
values because we get type safety when it comes to the properties we
explicitly specified.
interface Animal extends Record<string, any> { name: string; age: number; } const obj3: Animal = { name: 'Alfred', age: 3 }; // ⛔️ Error: Type 'number' is not // assignable to type 'string'. obj3.name = 5;
将属性设置为不正确的类型会导致错误,因为我们已经在接口中声明了该name
属性的类型。string
Animal