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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With