130
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
  • 1,454
  • 3
  • 10
  • 7

5 Answers5

195

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

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

}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – JAL Aug 10 '15 at 17:31
  • If all the parameters are of the same type, can you shorten this syntax? Something in the lines of f([a, b, c]: [number]) {...} – filipbarak Dec 10 '18 at 08:47
  • 6
    @filipbarak `f([a, b, c]: number[])` – Michael Mrozek Apr 29 '19 at 19:42
16

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]) {}
Marcelo Camargo
  • 2,240
  • 2
  • 22
  • 51
10

With TypeScript 4.0, tuple types can now provide labels

type Range = [start: number, end: number]
henriquehbr
  • 1,063
  • 4
  • 20
  • 41
7

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();
Rajnikant
  • 2,176
  • 24
  • 23
4

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

function f([a,b,c]: number[]) {}
Saurabh Thakur
  • 139
  • 3
  • 4