gpt4 book ai didi

TypeScript 映射类型值取决于键

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:09 25 4
gpt4 key购买 nike

我可以根据项目的键来限制 map 条目的值类型吗?

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 },
}

最佳答案

您要确保对于特定的 K,键的类型不是整个联合(即 T),而只是与输入 K。您可以使用 Extract 获取具有 K 类型属性 type 的联合成员:

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 },
}

关于TypeScript 映射类型值取决于键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com