You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript对象类型中根据OperationType切换properties类型不生效如何解决

问题原因

你当前的写法不生效的核心原因是:BaseModel<T>["operationType"] 本身是 'Insert' | 'Update' | 'Delete' 联合类型,"Update" extends 联合类型 的判断结果永远为真,所以 properties 的类型会被固定为 UpdateProperties<T>,无法和当前实例的 operationType 取值做关联。

实现方案

方案1:带泛型参数的实现

适合需要在类型层面明确指定操作类型的场景,代码如下:

type OperationType = 'Insert' | 'Update' | 'Delete';

// 新增泛型参数Op接收操作类型,默认值为全量OperationType
export type BaseModel<T extends Document, Op extends OperationType = OperationType> = {
  operationType: Op,
  properties: Op extends "Update" ? UpdateProperties<T> : Properties<T>,
  model: Model<T>,
  validation?: ValidateProp<T>
}

使用示例:

// 插入场景下properties自动对应Properties<T>类型
const insertModel: BaseModel<SomeDoc, 'Insert'> = {
  operationType: 'Insert',
  properties: // 此处会触发Properties<SomeDoc>的类型校验
  // 其余字段省略
}

方案2:区分联合类型实现

适合不需要显式传递泛型,靠字段取值自动收窄类型的场景,代码如下:

type OperationType = 'Insert' | 'Update' | 'Delete';

// 抽离公共字段定义
type BaseModelCommon<T extends Document> = {
  model: Model<T>,
  validation?: ValidateProp<T>
}

// 按操作类型拆分后组成联合类型
export type BaseModel<T extends Document> = 
  | (BaseModelCommon<T> & { operationType: 'Update', properties: UpdateProperties<T> })
  | (BaseModelCommon<T> & { operationType: Exclude<OperationType, 'Update'>, properties: Properties<T> })

使用示例:

// TS会自动根据operationType的取值收窄properties的类型
const updateModel = {
  operationType: 'Update',
  properties: // 自动推导为UpdateProperties<SomeDoc>类型
  model: // 其余字段省略
} satisfies BaseModel<SomeDoc>

内容的提问来源于stack exchange,提问作者Faizan Siddiqui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 03:15:01