Infer tuple type instead of union type

前端 未结 2 497
梦谈多话
梦谈多话 2020-12-21 12:53

Does anybody know how to make compiler to infer tuple type automatically ?

// Now: (string | number)[]
// Wanted: [string, number][]
const x = [ [\"a\", 2],          


        
2条回答
  •  梦毁少年i
    2020-12-21 13:21

    The compiler does not infer that, and there no way to force it to "know" it. the only thing that you can (And should do) is defined an interface that extends Array. like this:

    interface NumStrTuple extends Array {
        0: number;
        1: string;
        length: 2;
    }
    

    And use it to define your const like this:

    const x: NumStrTuple = [ ["a", 2], ["b", 2] ];
    

提交回复
热议问题