Types when destroying arrays

function f([a,b,c]) { // this works but a,b and c are any } 

is it possible to write something like that?

 function f([a: number,b: number,c: number]) { // being a, b and c typed as number } 
+7
arrays types destructuring typescript
source share
2 answers
 function f([a,b,c]: [number, number, number]) { } 

I have added text to this answer so that it does not appear in the VLQ code-only queue. As you can see, the question is basically β€œWhat is the syntax for this task?”, And the sample code above shows what the syntax looks like. Nothing to explain.

+17
source share

Yes it is. In TypeScript, you do this using array types in a simple way by creating tuples.

 type StringKeyValuePair = [string, string]; 

You can do what you want by naming the array:

 function f(xs: [number, number, number]) {} 

But you would not specify an intermediate parameter. Another possibility is to use pair destructuring:

 function f([a,b,c]: [number, number, number]) {} 
+4
source share

All Articles