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

TypeScript中boolean无法赋值给true类型的优雅解决方案咨询

解决TypeScript联合类型三元表达式返回的类型错误问题

你定义的联合类型:

type UnlockLevel = {
  unlocked: false;
  unlockLevel: number;
} | {
  unlocked: true;
  unlockLevel: undefined;
}

使用三元表达式返回时出现Type 'boolean' is not assignable to type 'true'错误,本质是TypeScript无法自动将boolean类型的unlocked变量窄化为联合类型要求的字面量true/false。以下是几种不丢失类型约束的优雅实现方式:

方案1:使用as const断言字面量类型

通过as const强制让编译器识别对象的字面量类型,精准匹配联合类型的分支:

function getUnlockData(level: number, unlockLevel: number): UnlockLevel {
  return level >= unlockLevel 
    ? { unlocked: true, unlockLevel: undefined } as const 
    : { unlocked: false, unlockLevel } as const;
}

方案2:显式断言联合类型分支

直接指定返回对象对应的联合类型分支,让编译器明确类型匹配关系:

function getUnlockData(level: number, unlockLevel: number): UnlockLevel {
  const unlocked = level >= unlockLevel;
  return unlocked 
    ? ({ unlocked: true, unlockLevel: undefined } as { unlocked: true; unlockLevel: undefined }) 
    : ({ unlocked: false, unlockLevel } as { unlocked: false; unlockLevel: number });
}

方案3:利用泛型条件类型推导

通过泛型条件类型自动推导返回类型,实现更简洁的写法:

function getUnlockData<T extends boolean>(level: number, unlockLevel: number): T extends true ? { unlocked: true; unlockLevel: undefined } : { unlocked: false; unlockLevel: number } {
  const unlocked = (level >= unlockLevel) as T;
  return unlocked 
    ? ({ unlocked: true, unlockLevel: undefined } as any) 
    : ({ unlocked: false, unlockLevel } as any);
}

注:此方式需用到any断言,适合追求极致简洁的场景。

内容的提问来源于stack exchange,提问作者Tan Grumser

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:49:54