Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Use `enum` values as `type`

I would like to use following enum's values:

export enum GenFormats {
    SHORT_LOWER = 'm/f', SHORT_UPPER = 'M/F', FULL = 'Male/Female'
};

as type given below:

export interface IGenderOptions {
    format: 'm/f' | 'M/F' | 'Male/Female'
};

by using Type extraction/definition something like:

{{some type cast/logic}}<GenFormats>    // Outputs: 'm/f' | 'M/F' | 'Male/Female'

Updated Question:

Here is my code:

export enum EGenderFormats {
    SHORT_LOWER = 'm/f', SHORT_UPPER = 'M/F', FULL = 'Male/Female'
};

export interface IGenderFormats {
    SHORT_LOWER: 'm/f'; SHORT_UPPER: 'M/F'; FULL: 'Male/Female';
};

export interface IGenderOptions {
    format: IGenderFormats[keyof IGenderFormats]
};

const DEFAULTS: IGenderOptions = {
    format: EGenderFormats.FULL
};

My question is, how can I use single entity either enum EGenderFormats or interface IGenderFormats instead of both?

I am using Typescript 3.2.2

Thanks

like image 575
Vikram Avatar asked Feb 15 '19 07:02

Vikram


People also ask

Can I use enum as a type in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Can we change enum values in TypeScript?

An enum is usually selected specifically because it is immutable - i.e. you would never want the values to change as it would make your application unpredictable.

Can I use TypeScript enum in JavaScript?

Enums are a feature added to JavaScript in TypeScript which makes it easier to handle named sets of constants. By default an enum is number based, starting at zero, and each option is assigned an increment by one. This is useful when the value is not important.


1 Answers

You can use the Enum as a type:

export enum EGenderFormats {
  SHORT_LOWER = "m/f",
  SHORT_UPPER = "M/F",
  FULL = "Male/Female"
}

type SGenderOptions = "m/f" | "M/F" | "Male/Female"

export interface IGenderOptions {
  format: EGenderFormats | SGenderOptions;
}

const DEFAULTS: IGenderOptions = {
  format: EGenderFormats.FULL
};

const OTHER_DEFAULTS: IGenderOptions = {
  format: "M/F"
};
like image 68
Dor Shinar Avatar answered Oct 12 '22 17:10

Dor Shinar