[英]Using Tuples in TypeScript (Type Inference)
Given this slightly artificial example:鉴于这个稍微人为的例子:
['List', 'Of', 'Names']
.map((name, index) => [name, index % 2])
.map(([name, num]) => );
why is name and num in the last line of type string | number
为什么
string | number
类型的最后一行是 name 和 num? 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? string | number
显然被推断为一个字符串和数字数组,你们知道是否有一种方法可以使用类型推断,以便 name 是一个字符串,num 分别是一个数字吗?
For arrays literals type inference does not infer tuples, it infers arrays, so对于数组文字类型推断不推断元组,它推断数组,所以
var foo = ["", 0]; // foo is Array<string | number> not [string, number]
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 and below solution 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 Solution 3.0 解决方案
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.
有关详细信息,请参阅PR 。 With this feature we can write a shorter version of the
tuple
function :有了这个特性,我们可以编写更短版本的
tuple
函数:
function tuple<T extends any[]> (...data: T){
return data;
}
['List', 'Of', 'Names']
.map((name, index) => tuple(name, index % 2))
.map(([name, num]) => name + "");
You can use a const assertion :您可以使用const 断言:
['List', 'Of', 'Names']
.map((name, index) => [name, index % 2] as const) // insert `as const` here
.map(([name, num]) => { }); // name: string, num: number
Take a look at the playground sample .看看操场示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.