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'
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
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.
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.
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.
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"
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With