Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Tuples in TypeScript (Type Inference)

Tags:

typescript

Given this slightly artificial example:

['List', 'Of', 'Names']
        .map((name, index) => [name, index % 2])
        .map(([name, num]) => );

why is name and num in the last line of type string | number obviously inferred as an Array of strings and numbers and do any of you know if there is a way to use type inference so that name is a string and num is a number respectively?

like image 674
cmart Avatar asked Nov 30 '22 14:11

cmart


1 Answers

You can use a const assertion:

['List', 'Of', 'Names']
    .map((name, index) => [name, index % 2] as const) // insert `as const` here
    .map(([name, num]) => { }); // name: string, num: number

Take a look at the playground sample.

like image 56
bela53 Avatar answered Dec 04 '22 07:12

bela53