Looking for a simpler way to create a TypeScript function that converts an enum to an array, including support for null
values.
Here's an example of what I'm trying to achieve:
enum Color
{
RED = "Red",
GREEN = "Green",
BLUE = "Blue"
}
let colors = convertEnumToArray(Color);
colors.push(null);
The expected type for colors
is (Color | null)[]
.
I came across a function in this article that almost fits my needs:
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'm wondering if there's a more straightforward approach available. Any suggestions?