繁体   English   中英

如何在打字稿中使用枚举作为索引键类型?

[英]How to use enum as index key type in typescript?

考虑以下示例。

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. 为什么我必须使用 'key in DialogType' 而不是 'key: DialogType'? (或者我可以吗?)
  1. |undefined不会使属性可选,只是意味着它可以是undefined ,有一个提议让|undefined成员可选,但目前它没有实现。 你需要使用? after ]使所有属性可选

    { [key in DialogType]?: Dialog }
  2. 您可以使用对话框枚举值作为键,但它们需要计算属性:

     let openDialogs: { [key in DialogType]?: Dialog } = { [DialogType.Options]: undefined, };
  3. { [key: number or string]: Dialog }是一个索引签名。 索引签名仅限于numberstring作为键类型(甚至两者的联合都不起作用)。 因此,如果您使用索引签名,则可以按任何numberstring进行索引(我们不能仅限于DialogType键)。 您在此处使用的概念称为映射类型。 映射类型基本上基于键的联合(在本例中为 DialogType 枚举的成员)和一组映射规则生成新类型。 我们上面创建的类型基本上等同于:

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

暂无
暂无

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

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