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 }
这是在参数列表中解构数组的正确语法:
function f([a,b,c]: [number, number, number]) { }
Yes, it is. In TypeScript, you do it with types of array in a simple way, creating tuples.
type StringKeyValuePair = [string, string];
您可以通过命名数组来完成您想要的操作:
function f(xs: [number, number, number]) {}
But you wouldn't name the interal parameter. 另一种可能性是成对使用解构:
function f([a,b,c]: [number, number, number]) {}
我的代码如下
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
在 TS2349下面的一行输入错误: 不能调用类型缺少调用签名的表达式;
nodes.map(x => { //some mapping; return x; );
把线改到下面解决了我的问题;
const [nodes, counts] = <Node[], number[]>getNodesAndCounts();
使用 TypeScript 4.0,元组类型现在可以提供标签
type Range = [start: number, end: number]
As a simple answer I would like to add that you can do this:
function f([a,b,c]: number[]) {}