typescript 解构数组时的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31923739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Types when destructuring arrays
提问by thr0w
function f([a,b,c]) {
// this works but a,b and c are any
}
it's possible write something like that?
有可能写出这样的东西吗?
function f([a: number,b: number,c: number]) {
// being a, b and c typed as number
}
回答by Ryan Cavanaugh
This is the proper syntax for destructuring an array inside an argument list:
这是在参数列表中解构数组的正确语法:
function f([a,b,c]: [number, number, number]) {
}
回答by Marcelo Camargo
Yes, it is. In TypeScript, you do it with types of array in a simple way, creating tuples.
是的。在 TypeScript 中,您可以通过一种简单的方式处理数组类型,即创建元组。
type StringKeyValuePair = [string, string];
You can do what you want by naming the array:
你可以通过命名数组来做你想做的事:
function f(xs: [number, number, number]) {}
But you wouldn't name the interal parameter. Another possibility is use destructuring by pairs:
但是您不会命名内部参数。另一种可能性是成对使用解构:
function f([a,b,c]: [number, number, number]) {}