Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array to a tuple in Typescript?

I have an array in a .js file and I want to use it as a tuple in a .ts file. It's a .js file because it's used by config files such as webpack.config.js. Is it possible to import it as a tuple?

E.g.:

entityTypes.js:

export default ['foo', 'bar'];

main.ts:

import type entityTypes from 'entityTypes';
typeof entityTypes[number]; // if `entityTypes` is a tuple, this would be 'foo' | 'bar'
like image 762
Leo Jiang Avatar asked Nov 01 '25 01:11

Leo Jiang


1 Answers

In general, Typescript does not analyze JS files, and it'll just type anything imported from there as any if no other type is given. Therefore it is impossible to type the array as a tuple without retyping all the strings.

However it is possible to export it as a tuple (if the exporting code would be typescript) with as const:

export default ['foo', 'bar'] as const;

It doesn't seem to be officially documented, but this blogpost describes it in detail.

like image 93
Jonas Wilms Avatar answered Nov 02 '25 15:11

Jonas Wilms