首页 > 解决方案 > TypeScript 处理类型数组或单个值

问题描述

我有一个这样的界面。我想知道处理这种情况的最佳情况是什么:

interface Ia {
  a: string
}
let a: Ia | Ia[]
console.log(a[0].a)

TS 给我一个错误:

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Ia'.
  Property '0' does not exist on type 'Ia'.

我知道我可以使用console.log((a as Ia[])[0].a),但它根本不可读。有没有人有更好的建议?

此外,真正的用例类型内部有许多属性,而不是a: sting示例中的单个属性。

标签: typescript

解决方案


如果a不是数组,则a[0]没有意义。您需要测试它是否是一个数组,并根据该测试的结果对其进行不同的处理。

interface Ia {
  a: string
}

let obj: Ia | Ia[] = { a: 'foo' };

function test(obj: Ia | Ia[]): void {
  console.log(Array.isArray(obj) ? obj[0].a : obj.a);
}

或者您可以使用这种利用控制流类型缩小的模式:

function test2(obj: Ia | Ia[]): void {
  if (Array.isArray(obj)) { obj = obj[0]; }
  // now obj: Ia is known not to be an array
  console.log(obj.a);
}

游乐场链接


推荐阅读