interface Ia {
  a: string
let a: Ia | Ia[]


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

    Playground Link