[英]Typescript: Use `enum` values as `type`
I would like to use following enum
's values:我想使用以下enum
的值:
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?我的问题是,如何使用单个实体enum EGenderFormats
或interface IGenderFormats
而不是两者?
I am using Typescript 3.2.2我正在使用 Typescript 3.2.2
Thanks谢谢
You can use the Enum as a type: 您可以将Enum用作一种类型:
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"
};
I think with the latest TypeScript you can just assign it.我认为最新的 TypeScript 你可以直接分配它。 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还有,在这里找答案,你一定会找到的:) https://blog.logrocket.com/typescript-string-enums-guide
typeof;)类型;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.