Types when destructuring arrays
37,814
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[]) {}
Related videos on Youtube
Author by
thr0w
Updated on July 30, 2022Comments
-
thr0w almost 2 years
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 }
-
thr0w almost 9 yearsI need different data types
-
-
JAL almost 9 yearsWhile this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
-
filipbarak over 5 yearsIf all the parameters are of the same type, can you shorten this syntax? Something in the lines of f([a, b, c]: [number]) {...}
-
Michael Mrozek about 5 years@filipbarak
f([a, b, c]: number[])