Types when destructuring arrays

ArraysTypesTypescriptDestructuring

Arrays Problem Overview


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 
}

Arrays Solutions


Solution 1 - Arrays

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

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

}

Solution 2 - Arrays

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 - Arrays

With TypeScript 4.0, tuple types can now provide labels

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

Solution 4 - Arrays

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 - Arrays

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionthr0wView Question on Stackoverflow
Solution 1 - ArraysRyan CavanaughView Answer on Stackoverflow
Solution 2 - ArraysMarcelo CamargoView Answer on Stackoverflow
Solution 3 - ArrayshenriquehbrView Answer on Stackoverflow
Solution 4 - ArraysRajnikantView Answer on Stackoverflow
Solution 5 - ArraysSaurabh ThakurView Answer on Stackoverflow