typescript - TypeScript 中的 Record 中只有多个可能键中的一个键

标签 typescript types

如果键只能是可能的字符串之一,如何获得对象键的自动完成功能?

在以下代码中,我收到所需的属性错误。 "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 playground

关于typescript - TypeScript 中的 Record 中只有多个可能键中的一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71881653/

相关文章:

angular - 需要帮助以了解我如何正确实现订阅

Angular post 请求发送 [object Object]

go - 如何检查值是否为 float

swift - 可以在 Swift 中将枚举类型名称作为参数传递吗?

generics - 如何在 "where"子句中给出表达式泛型类型?

typescript - 类型 'never[]' 不可分配给类型 '...'

angular - ngx-translate 与 ts 文件上的动态文本

haskell - 防止Haskell的类型变量增殖

node.js - "No such file or directory"在 Ubuntu 13.10 上运行 TypeScript

pointers - 戈朗 : Why selector to pointers is illegal after comparison?