简体   繁体   English

如何基于枚举结构为 object 创建类型

[英]How to create a type for object based on enum structure

I have a enum as below.我有一个枚举如下。

export enum Hotkey {
    MARK_IN = 'markIn',
    MARK_OUT = 'markOut',
    GO_TO_MARK_IN = 'goToMarkIn',
    GO_TO_MARK_OUT = 'goToMarkOut'
}

Now i want to create a type for a json object that should allow only the keys present in enum but not some random key during development.现在我想为 json object 创建一个类型,它应该只允许枚举中存在的键,而不是开发过程中的一些随机键。

type hotkey = keyof typeof Hotkey;

type clone = {[key:hotkey]: string}

const finalObject: clone = {
    MARK_IN : 'markIn'
};

i created the type as above but that is erroring out when i create the type "clone"我创建了上面的类型但是当我创建类型“克隆”时出错了

Error: An index signature parameter type cannot be a literal type or generic type.错误:索引签名参数类型不能是文字类型或泛型类型。 Consider using a mapped object type instead.ts(1337)考虑改用映射的 object 类型。ts(1337)

You can create a type using an enum for the key this way:您可以通过以下方式使用枚举为键创建类型:

export enum Hotkeys {
  MARK_IN = 'markIn',
  MARK_OUT = 'markOut',
  GO_TO_MARK_IN = 'goToMarkIn',
  GO_TO_MARK_OUT = 'goToMarkOut'
};

type IHotkey = `${ Hotkeys }`;

type IClone = {
  [key in IHotkey]?: string
};

If you want to use the enum member as the key you can also do:如果你想使用枚举成员作为键,你也可以这样做:

const yourObject: IClone = {
  [Hotkeys.MARK_IN] = 'your-value'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM