Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

typescript - Get array of string literal type values

I need to get a full list of all possible values for a string literal.

type YesNo = "Yes" | "No";
let arrayOfYesNo : Array<string> = someMagicFunction(YesNo); //["Yes", "No"]

Is there any way of achiving this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...