Get array of string literal type values

Enumeration may help you here:

enum YesNo {
    YES,
    NO
}

interface EnumObject {
    [enumValue: number]: string;
}

function getEnumValues(e: EnumObject): string[] {
    return Object.keys(e).map((i) => e[i]);
}

getEnumValues(YesNo); // ['YES', 'NO']

type declaration doesn’t create any symbol that you could use in runtime, it only creates an alias in type system. So there’s no way you can use it as a function argument.

If you need to have string values for YesNo type, you can use a trick (since string values of enums aren’t part of TS yet):

const YesNoEnum = {
   Yes: 'Yes',
   No: 'No'
};

function thatAcceptsYesNoValue(vale: keyof typeof YesNoEnum): void {}

Then you can use getEnumValues(YesNoEnum) to get possible values for YesNoEnum, i.e. [‘Yes’, ‘No’]. It’s a bit ugly, but that’d work.

To be honest, I would’ve gone with just a static variable like this:

type YesNo = 'yes' | 'no';
const YES_NO_VALUES: YesNo[] = ['yes', 'no'];

Leave a Comment