Change TypeScript array added to at runtime to union type

49 Views Asked by At

I need a union type in TypeScript that includes a known set of strings, plus additional strings added at runtime based on a variable value.

I've seen the solutions for a fixed array, like:

const list = ['a', 'b', 'c'] as const;
type listType = typeof list[number];

My problem is that to that list, I need to add N values such as 'd1', 'd2', up to 'dN', where N is a variable. And then I need to make a type of out the resulting array.

If I do something like this:

const list = ['a', 'b', 'c'] as const;
const list2 = [...list, 'd'] as const;
type listType = (typeof list2)[number];

it does work, (with or without parentheses around "typeof list2") - the type of list2 ends up as "a" | "b" | "d" | "c" - not sure why they are re-ordered, but obviously it doesn't matter.

Unfortunately that's not my real use case. My real use case is that what I need to add to the union of constants is the value of a variable (actually data read from a database). So the code ends up functionally like this (though any number of variable values might have to be added):

const list = ['a', 'b', 'c'] as const;
const s: string = 'd';
const list2 = [...list, s] as const;
type listType = (typeof list2)[number];

With that code, the type list2 is just string. Which is not what I want, I want the same result as the 1st example!

Actually, what I really want to add to the type is an unknown number of constant strings like 'custom1', 'custom2', etc., where the number of them is only known at runtime. I don't think that changes the problem.

1

There are 1 best solutions below

0
Cihad Paksoy On

Be careful with the use of parentheses:

const list = ['a', 'b', 'c'] as const;
const list2 = [...list, 'd1'] as const;

type list1Type = (typeof list)[number];
type list2Type = (typeof list2)[number];