3

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.