在 TypeScript 中为对象数组定义接口
要为对象数组定义接口,请为每个对象的类型定义接口,并将数组的类型设置为 Type[]
,例如 const arr: Employee[] = []
。 我们添加到数组中的所有对象都必须符合类型,否则类型检查器会出错。
// ✅ 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 },
];
在第一个示例中,我们使用接口定义了对象数组的类型。
每个对象都有一个数字类型的 id 属性和一个字符串类型的名称属性。
尝试将不同类型的对象添加到数组会导致类型检查器抛出错误。
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[]
。
// 👇️ const arr: any[]
const arr = [];
这意味着我们可以将任何类型的元素添加到数组中,并且我们不会从类型检查器获得任何帮助。
相反,我们应该显式键入所有空数组。
interface Employee {
id: number;
name: string;
}
const arr: Employee[] = [];
现在,你只能将符合 Employee
类型的对象添加到 arr 数组中。
如果我们事先不知道对象中所有属性的名称,请在我们的界面中使用索引签名。
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' });
当我们事先不知道类型属性的所有名称及其值的形状时,将使用索引签名。
示例中的索引签名意味着当对象被字符串索引时,它将返回任何类型的值。
我们可能还会在示例中看到索引签名 {[key: string]: string}
。 它代表一个键值结构,当用字符串索引时返回一个字符串类型的值。
现在我们知道数组中的每个元素都有一个数字类型的 id 属性,一个字符串类型的名称属性,但它也可以有其他属性,其中键是字符串,值可以是任何类型。
使用这种方法时,我们应该始终明确地将所有属性添加到事先知道的接口中。
最好尽量减少对 any
的使用,这样我们就可以尽可能多地利用类型检查器。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。