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

TypeScript条件类型守卫返回false时如何窄化为Child类型

实现方法

你当前的类型守卫仅声明了返回true时的判定规则,TypeScript无法默认关联返回false时的对应类型。只要明确所有User实例只能是Parent或Child两种类型之一,即可让守卫的否定分支自动缩窄为Child。

最优写法(适配原有使用习惯)

将原有User拆分为基础接口和联合类型即可,无需修改现有调用逻辑:

// 抽取公共属性作为基础接口
interface UserBase {
  email: string | null;
  name: string | null;
  isAdmin: boolean;
}

interface Parent extends UserBase {
  isAdmin: true;
}

interface Child extends UserBase {
  isAdmin: false;
  parent: string | null;
}

// 直接将User定义为两种子类型的联合
type User = Parent | Child;

// 类型守卫写法不变
const isAdmin = (user: User): user is Parent => user.isAdmin;

效果验证

使用时否定分支会自动缩窄类型:

function handleUser(user: User) {
  if (isAdmin(user)) {
    // 此处user类型为Parent
    console.log(user.email);
  } else {
    // 此处user类型自动判定为Child,可直接访问parent属性
    console.log(user.parent);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:15:02