gpt4 book ai didi

TypeScript:推断记录联合值

转载 作者:行者123 更新时间:2023-12-05 05:45:03 26 4
gpt4 key购买 nike

interface Num {
type: 'number',
default: number
}

interface Bool {
type: 'boolean'
default: boolean
}

interface Str {
type: 'string',
default: string
}

type UnionType = Num | Bool | Str

interface IOption<T extends string, CFG extends Record<T, UnionType>> {
configs: CFG,
// I don't know how to write this line to make each key matches its own value type
// i.e. `{key1: Num, key2: Bool, key3: Str}`
defaultOverwrite?: Partial<{ [key in T]: CFG[key]['default'] }>
}

declare function checker<T extends string, CFG extends Record<T, UnionType>>(option: IOption<T, CFG>): void

checker({
configs: {
// key1 errors as expected, which default should be a number
key1: { type: 'number', default: '' },
key2: { type: 'boolean', default: true },
key3: { type: 'string', default: 'string' },
},
defaultOverwrite: {
// the value of `key1` should match the type of configs.key1.default, which is a number.
// expected error here, but I don't know how
key1: '3'
}
})

见上例。

我想检查 configs 类型,哪个值应该匹配 UnionType,另外,我想检查 defaultOverwrite 类型,它应该有 configs 的部分键和 configs 声明的相应值类型。

但是我不知道怎么办,谁能帮帮我?

我重新考虑了我的问题,真正的问题是我们需要让联合值记录在赋值时成为精确类型,比如

type A = {[key: string]: string | number}
// when declared
const a: A = {
key1: 1,
key2: 'str'
}

我希望 a 匹配类型 A 但也生成一个确切的类型,即

interface ExactA{
key1: number,
key2: string
}

Playground

最佳答案

你不能指望在一个泛型中出现不止一个错误

defaultOverwrite 中的错误将在您修复 configs 中的错误后立即出现

checker({
configs: {
key1: { type: 'number', default: 1 }, // error fixed
key2: { type: 'boolean', default: true },
key3: { type: 'string', default: 'string' },
},
defaultOverwrite: {
key1: '1' // a new error has spawned
// (property) key1?: number | undefined
//Type 'string' is not assignable to type 'number'.(2322)
}
})

Playground

关于TypeScript:推断记录联合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71466522/

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