【问题标题】:Enum index signatures in TypeScript/ReactTypeScript/React 中的枚举索引签名
【发布时间】:2020-12-22 00:26:46
【问题描述】:

我似乎不知道如何在此处正确键入索引签名。我有一个枚举,需要遍历它以将一些 JSX 放在屏幕上。我可以猜到它在告诉我什么,但我无法在我的代码中解决它。 Category[el] 语句都有问题。

export enum Category {
    All = 'ALL',
    Employee = 'EMPLOYEE',
    Gear = 'GEAR',
    Room = 'ROOM',
    Other = 'OTHER',
}

我渲染一些 JSX 的简化函数是:

    const renderCategories = (): ReactElement | ReactElement[] => {
        return Object.keys(Category).map(el => {
            return (
                <Option key={el} value={Category[el]}>
                    <span>{` (${someOtherData.filter((e) => e.type === Category[el].length})`}</span>
                </Option>
            );
        });
    };

TS 告诉我:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Category'.
  No index signature with a parameter of type 'string' was found on type 'typeof Category'.

【问题讨论】:

    标签: reactjs typescript index-signature


    【解决方案1】:

    这种用例很常见,因为使用Object.keys 总是将每个键推断为string,这与enum 之类的键或具有特定类型的对象不兼容。

    但是 Typescript 仍然允许我们将每个键转换为一个类型,这意味着我们只是简单地转换回上述枚举的类型。

    这是反映上述解释的sn-p:

    export enum Category {
      All = 'ALL',
      Employee = 'EMPLOYEE',
      Gear = 'GEAR',
      Room = 'ROOM',
      Other = 'OTHER',
    }
    
    // A common type to detect the enum type
    
    type EnumType = typeof Category;
    type EnumKeyType = keyof EnumType;
    
    // Then cast back to our desired type
    
    someOtherData.filter((e) => e.type === Category[el as EnumKeyType].length) // cast `el as EnumKeyType`
    
    

    【讨论】:

    • 谢谢,我可以发誓我已经尝试过 keyof typeof 但它成功了。谢谢!
    【解决方案2】:

    您可以在枚举中添加以下索引签名:

    export enum Category {
        All = 'ALL',
        Employee = 'EMPLOYEE',
        Gear = 'GEAR',
        Room = 'ROOM',
        Other = 'OTHER',
        [key: string]: string,
    }
    

    【讨论】:

    • 不幸的是,我不能,因为我在最后一行收到以下错误:Enum member must have initializer.ts(1061) enums.ts(1164) 中不允许计算属性名称) 重复标识符 'string'.ts(2300)
    • 啊,我明白了,这实际上可能是这个的副本:stackoverflow.com/questions/47896885/iterate-on-string-enum
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多