type operation = 'create' | 'update' | 'delete';

type mutationKey = {
  operation: operation;
  id: K extends 'delete' | 'update' ? string : undefined; // want this field to be undefined if operation above is 'create'
}

// example 1
const ex1 = {
  operation: "create"
}

// example 2
const ex2 = {
  operation: "update",
  id: "1"
}

当我有条件地在对象中添加operation: "create"或任何其他操作时,有没有办法键入id字段?

推荐答案

在所有现有操作之间使用discriminated unions.这样,添加其他操作就很容易扩展.

interface CreateOperation {
  operation: 'create'
}


interface UpdateOperation {
  operation: 'update'
  id: string
}

interface DeleteOperation {
  operation: 'delete'
  id: string
}

type Operation =
  | CreateOperation
  | UpdateOperation
  | DeleteOperation

// example 1
const ex1: Operation = {
  operation: 'create',
}

// example 2
const ex2: Operation = {
  operation: 'update',
  id: "1"
}

Typescript相关问答推荐

需要使用相同组件重新加载路由变更数据—React TSX

如何创建泛型类型组件来使用React Native的FlatList或SectionList?'

如何缩小变量访问的对象属性范围?

如何正确地对类型脚本泛型进行限制

将对象属性转换为InstanceType或原样的强类型方法

Angular 错误NG0303在Angular 项目中使用app.Component.html中的NGFor

使用TypeScrip根据(可选)属性推断结果类型

TypeScrip-将<;A、B、C和>之一转换为联合A|B|C

了解类型规则中的关键字

在抽象类属性定义中扩展泛型类型

在构建Angular 应用程序时,有没有办法通过CLI传递参数?

重写返回任何

有没有什么方法可以使用ProvideState()提供多个削减器作为根减减器

类型脚本中函数重载中的类型推断问题

如何处理可能为空的变量...我知道这不是Null?

在tabel管理区域react js上设置特定顺序

为什么 Typescript 无法正确推断数组元素的类型?

有没有办法从不同长度的元组的联合中提取带有类型的最后一个元素?

node_modules/@newrelic/native-metrics:命令失败. node_modules/couchbase:命令失败.退出代码:127

如何推断深层嵌套属性的类型?