如何使用枚举作为打字稿中的索引键类型? [英] How to use enum as index key type in typescript?

查看:244
本文介绍了如何使用枚举作为打字稿中的索引键类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例.

enum DialogType {
    Options,
    Help
}

class Dialog { 
    test() : string {
        return "";
    }
}

class Greeter {

    openDialogs: { [key in DialogType]: Dialog | undefined } = {
        0: undefined,
        1: undefined
    };

    getDialog(t: DialogType) {
        return this.openDialogs[t];
    }
}

const greeter = new Greeter();
const d = greeter.getDialog(DialogType.Help);
if (d) document.write(d.test());

有3个问题/问题:

  1. 为什么即使我将属性声明为'|,我也不能忽略其初始值设定项中的属性.未定义"
  2. 为什么我不能使用'DialogType.Options'作为类型键,而必须使用硬编码数字?
  3. 为什么我必须使用"DialogType中的键"而不是"key:DialogType"? (或者可以吗?)

推荐答案

  1. |undefined不会将属性设为可选,只是表示它可以为undefined,有人建议将|undefined成员设为可选,但目前尚未实现.您需要在]之后使用?,以使所有属性为可选

  1. |undefined does not make a property optional, just means it can be undefined, there is a proposal to make |undefined members optional but currently it's not implemented. You need to use ? after ] to make all properties optional

{ [key in DialogType]?: Dialog }

  • 您可以将对话框枚举值用作键,但是需要计算它们的属性:

  • You can use the dialog enum values as keys, but they need to be computed properties:

    let openDialogs: { [key in DialogType]?: Dialog } = {
        [DialogType.Options]: undefined,
    };
    

  • { [key: number or string]: Dialog }是索引签名.索引签名仅限于numberstring作为密钥类型(甚至不能同时使用两者).因此,如果您使用索引签名,则可以通过任何numberstring进行索引(我们不能只限于DialogType键).您在此处使用的概念称为映射类型.映射类型基本上基于键的并集(在这种情况下为DialogType枚举的成员)和一组映射规则来生成新类型.我们上面创建的类型基本上等于:

  • { [key: number or string]: Dialog } is an index signature. Index signatures are restricted to only number or string as the key type (not even a union of the two will work). So if you use an index signature you can index by any number or string (we can't restrict to only DialogType keys). The concept you are using here is called mapped types. Mapped types basically generate a new type based on a union of keys (in this case the members of DialogType enum) and a set of mapping rules. The type we created above is basically equivalent to:

    let o: { [DialogType.Help]?: Dialog; [DialogType.Options]?: Dialog; }
    

  • 这篇关于如何使用枚举作为打字稿中的索引键类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆