Infer tuple type instead of union type

前端 未结 2 516
梦谈多话
梦谈多话 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条回答
  •  长情又很酷
    2020-12-21 13:30

    This can be done if we use an extra function to help type inference a bit:

    function tupleArray(arr:[T1, T2, T3][]) : typeof arr 
    function tupleArray(arr:[T1, T2][]) : typeof arr 
    function tupleArray(arr:[T1][]) : typeof arr 
    function tupleArray(arr:any[]) : any[]{
        return arr;
    }
    
    var t = tupleArray([ ["a", 2], ["b", 2] ]) // [string, number][]
    

    Edit

    Better version with fewer overrides:

    const tupleArray = (args: T): T => args
    tupleArray([["A", 1], ["B", 2]]) // [string, number][]
    

    You can add more overloads if you need more then 3 items in the tuple.

提交回复
热议问题