簡體   English   中英

TypeScript/React 中的枚舉索引簽名

[英]Enum index signatures in TypeScript/React

我似乎無法弄清楚如何在這里正確輸入索引簽名。 我有一個枚舉,需要遍歷它以將一些 JSX 放在屏幕上。 我可以猜到它在告訴我什么,但我無法在我的代碼中解決它。 Category[el]語句都是問題所在。

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

我簡化的 function 渲染一些 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'.

您可以將以下索引簽名添加到枚舉:

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

這個用例很常見,因為使用Object.keys總是將每個鍵推斷為與類似enum的鍵或具有特定類型的 object 的鍵不兼容的string

但是 Typescript 仍然允許我們將每個鍵轉換為一個類型,這意味着我們只是簡單地轉換回上述枚舉的類型。

這是反映上述解釋的片段:

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`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM