如果键只能是可能的字符串之一,如何获得对象键的自动完成功能?
在以下代码中,我收到所需的属性错误。 "must" is missing in type '{ must_not: any; }' but required in type 'Operator'.(2741)
type Operator = Record<"must" | "must_not", any>
const x : Operator = {
must: ...
}
const y : Operator = {
must_not: ...
}
我一次只能拥有一个键名称“must”或“must_not”。
最佳答案
您可以使用分布式条件类型 ( docs ) 创建单例对象的并集,每个键一个:
type SingletonUnion<K extends PropertyKey, T> = K extends any ? {[Key in K]: T} : never
(K extends PropertyKey
约束是为了防止错误使用,K extends any
约束是为了强制分配。)
type Operator = SingletonUnion<"must" | "must_not", any>
// type Operator = { must: any} | {must_not: any}
const x : Operator = {
must: 'any'
}
const y : Operator = {
must_not: 'any'
}
关于typescript - TypeScript 中的 Record 中只有多个可能键中的一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71881653/