Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert a string array to a string literal union type?

Tags:

typescript

Is it possible to convert this:

  const readonlyArray: readonly ['a', 'b', 'c'] = ['a', 'b', 'c'] as const;
  type DesiredType = typeof readonlyArray[number];

to something like:

  const array = ['a', 'b', 'c']; // this will come dynamically and sometimes it will be ['a', 'e', 'f']
  const readonlyArray = array as const;
  type DesiredType = typeof readonlyArray[number];

I think this is not possible, but do you have a similar solution that will do the same work?


Here is the simplified version of the real world problem:

I have a React component with 2 props - status: 'a' | 'b', renamedPropB?: string and if you change the renamedPropB from undefined to let's say 'Z' the type of the status should become 'a' | 'Z' instead of the original 'a' | 'b'.

And the idea is to have the string literals in the union in an string array so it will be dynamic and easier to change the 'b' to 'Z' as well as to add more or remove existing string literals from the union.

like image 795
Nikolai Avatar asked Jan 25 '26 17:01

Nikolai


1 Answers

You can't apply as const after the fact. It has to be done at the time the array or object is created.

If the array is coming from an external source then I believe the answer is no, this can't be done. You can always get the type of the elements in the array, but if the array is created as string[] then the element type will be string, not the literal values.

like image 185
Linda Paiste Avatar answered Jan 27 '26 09:01

Linda Paiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!