有人知道如何使编译器自动推断元组类型吗?

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

最佳答案

如果我们使用一个额外的函数来帮助类型推断,就可以做到这一点:

function tupleArray<T1, T2, T3>(arr:[T1, T2, T3][]) : typeof arr
function tupleArray<T1, T2>(arr:[T1, T2][]) : typeof arr
function tupleArray<T1>(arr:[T1][]) : typeof arr
function tupleArray(arr:any[]) : any[]{
    return arr;
}

var t = tupleArray([ ["a", 2], ["b", 2] ]) // [string, number][]

编辑
更好的版本,覆盖更少:
const tupleArray = <T extends ([any] | any[])[]>(args: T): T => args
tupleArray([["A", 1], ["B", 2]]) // [string, number][]

如果元组中需要多于3个项,则可以添加更多重载。

关于typescript - 推断元组类型而不是联合类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48872328/

10-09 22:00
查看更多