解构数组时的类型

thr*_*r0w 36 arrays types destructuring typescript

function f([a,b,c]) {
  // this works but a,b and c are any
}
Run Code Online (Sandbox Code Playgroud)

有可能写出类似的东西吗?

function f([a: number,b: number,c: number]) {
  // being a, b and c typed as number 
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ugh 66

function f([a,b,c]: [number, number, number]) {

}
Run Code Online (Sandbox Code Playgroud)

我已在此答案中添加了文本,因此它不会显示在"仅代码"VLQ队列中.正如您所看到的,问题基本上是"此任务的语法是什么?",上面的代码示例显示了语法的样子.没有什么可以解释的.

  • @filipbarak `f([a, b, c]: number[])` (3认同)

Mar*_*rgo 10

是的.在TypeScript中,您可以通过简单的方式使用数组类型创建元组.

type StringKeyValuePair = [string, string];
Run Code Online (Sandbox Code Playgroud)

您可以通过命名数组来执行您想要的操作:

function f(xs: [number, number, number]) {}
Run Code Online (Sandbox Code Playgroud)

但是你不会命名interal参数.另一种可能性是成对使用解构:

function f([a,b,c]: [number, number, number]) {}
Run Code Online (Sandbox Code Playgroud)


RAJ*_*RAJ 7

我的代码如下

type Node = { 
    start: string;
    end: string;
    level: number;
};

const getNodesAndCounts = () => { 
    const nodes : Node[]; 
    const counts: number[];
    // ... code here

return [nodes, counts];
}

const [nodes, counts] = getNodesAndCounts(); // problematic line needed type
Run Code Online (Sandbox Code Playgroud)

打字稿在 TS2349 下面的行中给了我错误:无法调用其类型缺少调用签名的表达式;

nodes.map(x => { 
//some mapping; 
    return x;
);
Run Code Online (Sandbox Code Playgroud)

将行更改为下面解决了我的问题;

const [nodes, counts] = <Node[], number[]>getNodesAndCounts();
Run Code Online (Sandbox Code Playgroud)


Hen*_*HBR 6

使用 TypeScript 4.0,元组类型现在可以提供标签

type Range = [start: number, end: number]
Run Code Online (Sandbox Code Playgroud)


小智 5

作为一个简单的答案,我想补充一点,你可以这样做:

function f([a,b,c]: number[]) {}
Run Code Online (Sandbox Code Playgroud)