在 TypeScript 中为对象数组定义接口

在 TypeScript 中为对象数组定义接口

Define an Interface for Array of Objects in TypeScript

要为对象数组定义接口,请为每个对象的类型定义接口并将数组的类型设置为Type[],例如
const arr: Employee[] = []您添加到数组中的所有对象都必须符合类型,否则类型检查器会出错。

索引.ts
// ✅ All objects have predefined type interface Employee { id: number; name: string; } const arr: Employee[] = [ { id: 1, name: 'Tom' }, { id: 2, name: 'Jeff' }, ]; // ✅ Objects with extendable type interface Extendable { id: number; name: string; [key: string]: any; // 👈️ index signature } const arr2: Extendable[] = [ { id: 1, name: 'Tom' }, { id: 2, name: 'Jeff', salary: 100 }, ];

在第一个示例中,我们使用接口定义了对象数组的类型。

每个对象都有一个idtype属性number和一个typename属性
string

尝试将不同类型的对象添加到数组会导致类型检查器抛出错误。

索引.ts
interface Employee { id: number; name: string; } const arr: Employee[] = [ { id: 1, name: 'Tom' }, { id: 2, name: 'Jeff' }, ]; // ⛔️ Error: Argument of type '{ salary: number; }' // is not assignable to parameter of type 'Employee'. arr.push({ salary: 100 });

当您必须将数组初始化为空时,这种方法非常有用。如果您初始化一个空数组,TypeScript 会假定其类型为any[].

索引.ts
// 👇️ const arr: any[] const arr = [];

这意味着您可以将anytype 的元素添加到数组中,并且您不会从类型检查器获得任何帮助。

相反,您应该显式键入所有空数组。

索引.ts
interface Employee { id: number; name: string; } const arr: Employee[] = [];

现在,你只能将符合Employee类型的对象添加到arr
数组中。

如果您事先不知道对象中所有属性的名称,请在您的界面中使用索引签名。

索引.ts
interface Employee { id: number; name: string; [key: string]: any; // 👈️ index signature } const arr: Employee[] = [ { id: 1, name: 'Tom' }, { id: 2, name: 'Jeff', salary: 100 }, ]; arr.push({ id: 3, name: 'Adam', dept: 'accounting' });


当我们事先不知道类型属性的所有名称及其值的形状时,将使用
索引
签名。

The index signature in the example means that when an the object is indexed with a string, it will return a value of any type.

You might also see the index signature {[key: string]: string} in examples. It
represents a key-value structure that when indexed with a string returns a
value of type string.

Now we know that every element in the array will have an id property of type
number, a name property of type string, but it can also have other
properties where the key is a string and the value could be of any type.

When using this approach, you should always explicitly add all of the properties
to the interface that you know about in advance.

It’s best to minimize your use of any, so we can leverage the type checker as
much as possible.