Reputation: 1544
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
}
Upvotes: 139
Views: 66758
Reputation: 149
As a simple answer I would like to add that you can do this:
function f([a,b,c]: number[]) {}
Upvotes: 5
Reputation: 1122
With TypeScript 4.0, tuple types can now provide labels
type Range = [start: number, end: number]
Upvotes: 13
Reputation: 2236
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();
Upvotes: 7
Reputation: 220944
This is the proper syntax for destructuring an array inside an argument list:
function f([a,b,c]: [number, number, number]) {
}
Upvotes: 205
Reputation: 2298
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]) {}
Upvotes: 17