Reputation: 632
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
Upvotes: 14
Views: 14160
Reputation: 672
this is an old question but none of the answers really answering it, maybe you looking for:
keyof typeof EGenderFormats
Upvotes: 2
Reputation: 362
I think with the latest TypeScript you can just assign it. This is how I set up my easy-peasy store in an app for pages using enum
import { Action, action, createStore } from "easy-peasy";
import { createTypedHooks } from "easy-peasy";
interface IStoreModel {
page: Pages;
setPage: Action<IStoreModel, Pages>;
}
enum Pages {
Home = "home",
Admin = "admin",
}
const typedHooks = createTypedHooks<IStoreModel>();
const store = createStore<IStoreModel>({
page: Pages.Admin,
setPage: action((state, payload) => {
state.page = payload;
}),
});
export const useStoreActions = typedHooks.useStoreActions;
export const useStoreDispatch = typedHooks.useStoreDispatch;
export const useStoreState = typedHooks.useStoreState;
Also, look here for the answer, you will definitely find it :)
https://blog.logrocket.com/typescript-string-enums-guide
typeof ;)
Upvotes: 2
Reputation: 1512
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"
};
Upvotes: 7