一种常见的TS错误是在遍历对象数组时出现的。这通常发生在使用for循环时,因为TS不能确定数组中的每个元素是否包含所需的属性。
为了解决这个问题,我们可以使用类型断言或as关键字来告诉TS变量的类型。例如,假设我们有一个people数组,每个元素都包含name和age属性。
const people = [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 35 }, { name: 'Charlie', age: 40 }, ];
我们可以使用类型断言将数组元素的类型指定为具有name和age属性的对象。
for (const person of people) { console.log(person.name, person.age); }
或者,我们可以使用as关键字指定person变量的类型。
for (const person of people) { const { name, age } = person as { name: string, age: number }; console.log(name, age); }
通过这些方法,我们可以避免TS在遍历对象数组时发生错误。