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'.

I know I could use console.log((a as Ia[])[0].a) but it is not readable at all. Does anyone have better suggestions?

Also, the real use case type has many properties inside not the single one a: sting as in the example.

评论
  • 陌上桑
    陌上桑 回复

    If a is not an array, then a[0] does not make sense. You need to test whether it is an array, and treat it differently depending on the result of that test.

    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);
    }
    

    Playground Link