推断元组类型而不是联合类型 [英] Infer tuple type instead of union type

查看:44
本文介绍了推断元组类型而不是联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

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

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

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][]

编辑

更好的版本,更少的覆盖:

Better version with fewer overrides:

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

如果元组中需要超过 3 个项目,您可以添加更多重载.

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

这篇关于推断元组类型而不是联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆