Flowtype 中 Typescript 的 "key in EnumType" 是什么?
What's the equivalent of Typescript's "key in EnumType" in Flowtype?
Typescript 允许我编写这样的代码:
export enum ActivityType {
FREERIDE = "FREERIDE",
SKI_TOUR = "SKI_TOUR",
}
const activityDesctription: {
[key in ActivityType]: string
} = {
[ActivityType.FREERIDE]: "Freeriding",
[ActivityType.SKI_TOUR]: "Ski-touring"
};
in
表达式为我提供了非常严格的类型安全性,即 activityDescription 必须包含枚举的每个成员的定义,不能少,不能多。它还会生成适当的索引运算符。
如何在 Flowtype 中进行 in
表达式?
更新答案
如果您希望 activityDescription
与 完全 与 ActivityType
相同的键并在丢失某些键时抱怨,请使用 $ObjMap
(docs). Flow try
const ActivityType = {
FREERIDE: "FREERIDE",
SKI_TOUR: "SKI_TOUR",
}
type StringValue = <V>(V) => string
const activityDescription: $ObjMap<typeof ActivityType, StringValue> = {
[ActivityType.FREERIDE]: 'yo',
[ActivityType.SKI_TOUR]: 'this is fun',
}
旧答案
您可以使用 $Keys<typeof obj>
来提取对象的键。 Docs, and Flow try.
更新:如评论中所述,当 activityDescription
.
中缺少 ActivityType
的键时,此解决方案不会引发编译错误
const ActivityType = {
FREERIDE: "FREERIDE",
SKI_TOUR: "SKI_TOUR",
}
const activityDescription: {
[$Keys<typeof ActivityType>]: string
} = {
[ActivityType.FREERIDE]: "Freeriding",
[ActivityType.SKI_TOUR]: "Ski-touring",
error: 'error' // flow errors here
};
Typescript 允许我编写这样的代码:
export enum ActivityType {
FREERIDE = "FREERIDE",
SKI_TOUR = "SKI_TOUR",
}
const activityDesctription: {
[key in ActivityType]: string
} = {
[ActivityType.FREERIDE]: "Freeriding",
[ActivityType.SKI_TOUR]: "Ski-touring"
};
in
表达式为我提供了非常严格的类型安全性,即 activityDescription 必须包含枚举的每个成员的定义,不能少,不能多。它还会生成适当的索引运算符。
如何在 Flowtype 中进行 in
表达式?
更新答案
如果您希望 activityDescription
与 完全 与 ActivityType
相同的键并在丢失某些键时抱怨,请使用 $ObjMap
(docs). Flow try
const ActivityType = {
FREERIDE: "FREERIDE",
SKI_TOUR: "SKI_TOUR",
}
type StringValue = <V>(V) => string
const activityDescription: $ObjMap<typeof ActivityType, StringValue> = {
[ActivityType.FREERIDE]: 'yo',
[ActivityType.SKI_TOUR]: 'this is fun',
}
旧答案
您可以使用 $Keys<typeof obj>
来提取对象的键。 Docs, and Flow try.
更新:如评论中所述,当 activityDescription
.
ActivityType
的键时,此解决方案不会引发编译错误
const ActivityType = {
FREERIDE: "FREERIDE",
SKI_TOUR: "SKI_TOUR",
}
const activityDescription: {
[$Keys<typeof ActivityType>]: string
} = {
[ActivityType.FREERIDE]: "Freeriding",
[ActivityType.SKI_TOUR]: "Ski-touring",
error: 'error' // flow errors here
};