你想确保某个特定的
K
钥匙的类型不是整个接头(即
T
)而是工会的成员
K
.你可以用
Extract
得到拥有财产的工会成员
type
类型
K
:
type Thing<T extends string = any> = {
type: T
}
type ThingMap<T extends Thing> = {
[K in T["type"]]: Extract<T, { type : K }> // Extract the union member that has { type: K }
}
interface A {
type: "A",
foo: boolean,
}
interface B {
type: "B",
}
// This compiles.
const map: ThingMap<A | B> = {
A: { type: "A", foo: true },
B: { type: "B" },
}
// Err now
const map2: ThingMap<A | B> = {
A: { type: "A", foo: true },
B: { type: "A", foo: true },
}