Types when destructuring arrays

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 
}

Solution 1:

This is the proper syntax for destructuring an array inside an argument list:

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

}

Solution 2:

Yes, it is. In TypeScript, you do it with types of array in a simple way, creating tuples.

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]) {}

Solution 3:

With TypeScript 4.0, tuple types can now provide labels

type Range = [start: number, end: number]

Solution 4:

my code was something like below

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

typescript was giving me error in line below TS2349: Cannot invoke an expression whose type lacks a call signature;

nodes.map(x => { 
//some mapping; 
    return x;
);

Changing line to below resolved my problem;

const [nodes, counts] = <Node[], number[]>getNodesAndCounts();

Solution 5:

As a simple answer I would like to add that you can do this:

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