我可以根据项目的键约束地图条目的值类型吗?
type Thing<T extends string = any> = {
type: T
}
type ThingMap<T extends Thing> = {
[K in T["type"]]: T
}
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" },
}
// But this also compiles, when it should not.
const map: ThingMap<A | B> = {
A: { type: "A", foo: true },
B: { type: "A", foo: true },
}
答案 0 :(得分:2)
您要确保对于特定的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 },
}