我有一个接口,键作为枚举,其他接口作为值。
enum Enum {
Val1, Val2, Val3
}
interface MyInterface {
[Enum.Val1]: { bookingId: string }
[Enum.Val2]: { videoId: string }
[Enum.Val3]: { userId: string }
}
有了它们,我有了一个相关的模型:
const EVENT_TASK_MODEL = {
A: {
a: [Enum.Val1, Enum.Val2],
},
B: {
c: [Enum.Val2, Enum.Val3]
}
} as const
基于上面的模型,我想创建一个并集,根据提供的键组合MyInterface
的每个键的值。如下所示:
CombinedModel<"A", "a"> // { bookingId: string } | { videoId: string }
说明:
EVENT_TASK_MODEL["A"]["a"] = [Enum.Val1, Enum.Val2]
Look up values in MyInterface: MyInterface[Enum.Val1] and MyInterface[Enum.Val2]
Their values are: { bookingId: string } and { videoId }
Create union: { bookingId: string } | { videoId: string }
我们需要创建一个具有两个泛型参数K1
和K2
的泛型类型。它们被约束为typeof EVENT_TASK_MODEL
中的有效路径。
type CombinedModel<
K1 extends keyof typeof EVENT_TASK_MODEL,
K2 extends keyof typeof EVENT_TASK_MODEL[K1]
> =
typeof EVENT_TASK_MODEL[K1][K2] extends infer U extends readonly (keyof MyInterface)[]
? MyInterface[U[number]]
: never
我们用K1
和K2
对EVENT_TASK_MODEL
进行索引,并将结果存储在U
中。通过添加这个额外的extends readonly (keyof MyInterface)[]
,我们提醒TypeScriptU
的形状应该是什么。最后,我们通过用number
对存储在U
中的元组进行索引来创建一个并集,并使用该并集对MyInterface
进行索引。
type T0 = CombinedModel<"A", "a">
// type T0 = {
// bookingId: string;
// } | {
// videoId: string;
// }
type T1 = CombinedModel<"B", "c">
// type T1 = {
// videoId: string;
// } | {
// userId: string;
// }
游乐场