typescript类型基于Extract产生的类型推断问题

以下代码:

// 联合类型
type TBool = {
  success: Extract<boolean, true>;
} | {
  success: Extract<boolean, false>;
  error: number;
}

// 将特定字段转换为非必填
type WithoutId<T> = Omit<T, 'id'> & {id?: string};

// 类型定义
type Demo = {
  id: string;
} & TBool;

// 这个用法下无法基于success是false进一步推断
const data: WithoutId<Demo> = {
  success: false,
  error: 500, // error不在类型WithoutId<Demo>中
}

// 但是不使用WithoutId就正常了
const idData: Demo = {
  id: '5',
  success: false,
  error: 500,
}

是WithoutId的问题吗?还是我对联合类型的用法理解上有问题?typescript 4.5.5

感谢楼下的回答,通过以下的方式可以实现了。


type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;

// 联合类型
type TBool = {
  success: Extract<boolean, true>;
} | {
  success: Extract<boolean, false>;
  error: number;
}

// 将特定字段转换为非必填
type WithoutId<T> = DistributiveOmit<T, 'id'> & {id?: string};

// 类型定义
type Demo = {
  id: string;
} & TBool;

// 现在正常了
const data: WithoutId<Demo> = {
  success: false,
  error: 500,
}

const data2: WithoutId<Demo> = {
  success: true,
}
阅读 1.7k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进