如何将枚举的类型重构为在流类型中使用的泛型?
How to refactor an enum's type to generic using in flowtype?
假设我有 3 个枚举类型为 {[key: string]: Type}
这很常见
我在想这样的事情:
export interface KeyType<T> {
[key: string]: T;
}
并像这样使用它:
KeyType<HeadingOptionType>
但它不起作用:(。
我如何编写一个类型来删除下面示例中的 {[key: string]}
重复?
export const HeadingOption: {[key: string]: HeadingOptionType} = {
H1: 1,
H2: 2,
H3: 3,
H4: 4,
H5: 5,
H6: 6,
};
export const EnumColumn: {[key: string]: EnumColumnType} = {
C1: 1,
C2: 2,
C3: 3,
C4: 4, // not supported yet but should be.
};
export const RtlMirror: {[key: string]: RtlMirrorType} = {
ON: true,
OFF: false,
};
我猜你遇到了关于索引器 属性 的错误。您可以通过将界面更改为类型别名来摆脱它:type KeyType<T> = { [string]: T };
。
无论如何,我认为这样的输入没有用,因为您需要手动定义值类型。流程中描述枚举的常见做法是:
const HEADING_OPTION = Object.freeze({
H1: 1,
H2: 2,
H3: 3,
H4: 4,
H5: 5,
H6: 6,
});
type HeadingOption = $Values<typeof HEADING_OPTION>;
let h1: HeadingOption = HEADING_OPTION.H1; // OK
h1 = 1; // OK
// $Expect error: Cannot assign `999` to `h1` because number is incompatible with enum
h1 = 999;
假设我有 3 个枚举类型为 {[key: string]: Type}
这很常见
我在想这样的事情:
export interface KeyType<T> {
[key: string]: T;
}
并像这样使用它:
KeyType<HeadingOptionType>
但它不起作用:(。
我如何编写一个类型来删除下面示例中的 {[key: string]}
重复?
export const HeadingOption: {[key: string]: HeadingOptionType} = {
H1: 1,
H2: 2,
H3: 3,
H4: 4,
H5: 5,
H6: 6,
};
export const EnumColumn: {[key: string]: EnumColumnType} = {
C1: 1,
C2: 2,
C3: 3,
C4: 4, // not supported yet but should be.
};
export const RtlMirror: {[key: string]: RtlMirrorType} = {
ON: true,
OFF: false,
};
我猜你遇到了关于索引器 属性 的错误。您可以通过将界面更改为类型别名来摆脱它:type KeyType<T> = { [string]: T };
。
无论如何,我认为这样的输入没有用,因为您需要手动定义值类型。流程中描述枚举的常见做法是:
const HEADING_OPTION = Object.freeze({
H1: 1,
H2: 2,
H3: 3,
H4: 4,
H5: 5,
H6: 6,
});
type HeadingOption = $Values<typeof HEADING_OPTION>;
let h1: HeadingOption = HEADING_OPTION.H1; // OK
h1 = 1; // OK
// $Expect error: Cannot assign `999` to `h1` because number is incompatible with enum
h1 = 999;