Is there a way to create a generic function in TypeScript to convert an enum to an array that also accepts null
values?
Something like this:
enum Color
{
RED = "Red",
GREEN = "Green",
BLUE = "Blue"
}
let colors = convertEnumToArray(Color);
colors.push(null);
Where colors
is of type (Color | null)[]
.
I've found the function below in this link and I'd like to modify it to allow null
in the array:
https://blog.oyam.dev/typescript-enum-values/
type EnumObject = {[key: string]: number | string};
type EnumObjectEnum<E extends EnumObject> = E extends {[key: string]: infer ET | string} ? ET : never;
function convertEnumToArray<E extends EnumObject>(enumObject: E): Array<EnumObjectEnum<E> | null> {
const elements = Object.values(enumObject)
.filter(key => Number.isNaN(Number(key)))
.map(key => enumObject[key] as (EnumObjectEnum<E> | null));
elements.unshift(null);
return elements;
}
But I think there should be an easier way, or am I wrong?