【问题标题】:How to use enum as index key type in typescript?如何在打字稿中使用枚举作为索引键类型?
【发布时间】:2019-03-13 00:42:49
【问题描述】:

考虑以下示例。

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());

Also in playground

它有 3 个问题/问题:

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

【问题讨论】:

标签: typescript dictionary indexing enums


【解决方案1】:
  1. |undefined 没有使属性可选,只是意味着它可以是undefined,有一个建议使|undefined 成员可选,但目前尚未实现。您需要在] 之后使用? 以使所有属性都可选

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

【讨论】:

  • 太棒了,非常感谢!我确信'T?相当于'T | undefined',尤其是在看到这个之后:typescriptlang.org/docs/handbook/…。那么可选类型是等价于某种东西还是它本身就是一种东西?
  • @ironic 它是一种方式,但不是另一种方式,T? 类型的属性将被视为T|undefined 用于空检查,但T|undefined 类型的属性不会被视为可选
  • 我想为每个键指定不同的成员类型是什么 id?类似:let o: { [DialogType.Help]: DialogHelp; [DialogType.Options]: DialogOptions; }
  • @neomib 您可以像在您的示例中一样手动执行此操作,如果有一些映射规则我需要查看它以提供更好的解决方案
  • 谢谢!我意识到在commeting之后;)
猜你喜欢
  • 2021-06-02
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 2020-12-09
  • 2019-12-27
  • 1970-01-01
相关资源
最近更新 更多