I want to have an array or set of values that is guaranteed to have all values of a string union. I know that I can do the reverse (TypeScript String Union to String Array) but in my case, the types are coming from a library.
So, imagine you have a union of strings given
type A = 'foo' | 'bar';
Now you want to create an array or set that has all values of the union of strings (not more or less).
const a = ['foo', 'bar'];
should pass because it has all valuesconst a = ['foo'];
should fail because 'bar' is missingconst a = ['foo', 'bar', 'baz'];
should fail becausebaz
is not a validA
. This one is easy:const a: A[] = ['foo', 'bar', 'baz'];
.
Since type information is lost at runtime, I know that I have to list the keys manually but I am okay with that.
I am aware of a trick, which works for objects but I would like to have something similar to arrays or sets.
type Flag<S extends string> = {[K in S]: 1};
const a = Flag<A> = {
foo: 1,
bar: 1
}
EDIT: here is a related issue on Typescript: https://github.com/microsoft/TypeScript/issues/13298