簡體   English   中英

Typescript:使用“枚舉”值作為“類型”

[英]Typescript: Use `enum` values as `type`

我想使用以下enum的值:

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

作為下面給出的類型:

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

通過使用類型提取/定義,例如:

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

更新問題:

這是我的代碼:

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
};

我的問題是,如何使用單個實體enum EGenderFormatsinterface IGenderFormats而不是兩者?

我正在使用 Typescript 3.2.2

謝謝

您可以將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"
};

我認為最新的 TypeScript 你可以直接分配它。 這就是我在應用程序中使用枚舉為頁面設置簡單商店的方式

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;

還有,在這里找答案,你一定會找到的:) https://blog.logrocket.com/typescript-string-enums-guide
類型;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM