在 TypeScript 中使用元组(类型推断) [英] Using Tuples in TypeScript (Type Inference)

查看:33
本文介绍了在 TypeScript 中使用元组(类型推断)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举这个稍微人为的例子:

Given this slightly artificial example:

['List', 'Of', 'Names']
        .map((name, index) => [name, index % 2])
        .map(([name, num]) => );

为什么string 类型的最后一行是name 和num?number 显然被推断为字符串和数字的数组,你们中的任何人都知道是否有一种方法可以使用类型推断,以便 name 是一个字符串,num 分别是一个数字?

why is name and num in the last line of type string | number obviously inferred as an Array of strings and numbers and do any of you know if there is a way to use type inference so that name is a string and num is a number respectively?

推荐答案

对于数组字面量类型推断不推断元组,它推断数组,所以

For arrays literals type inference does not infer tuples, it infers arrays, so

var foo = ["", 0]; // foo is Array<string | number> not [string, number]

我没有找到这方面的文档,但是 pull request 从未添加对元组的支持在声明它们时使用推理,我猜这是故意的.

I have not found documentation on this but the pull request adding support for tuples never uses inference when declaring them, I'm guessing this is deliberate.

在您的情况下,您可以指定类型参数:

In your case you can specify the type parameter:

['List', 'Of', 'Names']
        .map<[string, number]>((name, index) => [name, index % 2])
        .map(([name, num]) => name + "");

2.9 及以下解决方案

或者创建一个元组辅助函数,如果这对您来说是一个常见问题:

Or create a tuple helper function if this is a common issue for you:

function tuple<T1, T2, T3, T4, T5>(data: [T1, T2, T3, T4, T5]) : typeof data
function tuple<T1, T2, T3, T4>(data: [T1, T2, T3, T4]) : typeof data
function tuple<T1, T2, T3>(data: [T1, T2, T3]) : typeof data
function tuple<T1, T2>(data: [T1, T2]) : typeof data
function tuple(data: Array<any>){
    return data;
}

['List', 'Of', 'Names']
        .map((name, index) => tuple([name, index % 2]))
        .map(([name, num]) => name + "");

3.0 解决方案

自从我发布原始答案打字稿以来,它改进了推断其余参数的元组类型的能力.有关详细信息,请参阅 PR.有了这个特性,我们可以编写一个较短版本的 tuple 函数:

Since I posted the original answer typescript has improved it's inference with the ability to infer tuple types for rest parameters. See PR for details. With this feature we can write a shorter version of the tuple function :

function tuple<T extends any[]> (...data: T){
    return data;
}

['List', 'Of', 'Names']
        .map((name, index) => tuple(name, index % 2))
        .map(([name, num]) => name + "");

这篇关于在 TypeScript 中使用元组(类型推断)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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