简体   繁体   中英

How to define finite set of 5 elements in typescript?

I am trying to construct a type in TypeScript that denotes a finite set using other types, let's say of exactly 5 values?(And it's not enum).

For example :

Boolean = {TRUE,FALSE} 

You can define a literal union type. Example:

type LiteralType = "ONE" | 2 | "Three" | 4 | "5";

Any variable declared as LiteralType can only have one of the above five values:

let x: LiteralType;
x = 2; // OK
x = "Two"; // Error

Union/literal types documentation: https://www.typescriptlang.org/docs/handbook/advanced-types.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM