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

如何创建可区分statusCode为'0000'或非'0000'的TS判别式联合类型

TypeScript 判别式联合类型实现状态码区分

要实现你需要的判别式联合类型,可以利用TypeScript的Exclude工具类型定义非'0000'的字符串类型,通过statusCode的值自动推断对应对象结构:

type SuccessResponse = {
  statusCode: '0000';
  something: string;
};

type ErrorResponse = {
  statusCode: Exclude<string, '0000'>;
  somethingElse: string;
};

type Foo = SuccessResponse | ErrorResponse;

用法示例

检查statusCode时,TypeScript会自动缩小类型范围:

function handleResponse(response: Foo) {
  if (response.statusCode === '0000') {
    // 此处response被推断为SuccessResponse,可访问something
    console.log(response.something);
  } else {
    // 此处response被推断为ErrorResponse,可访问somethingElse
    console.log(response.somethingElse);
  }
}

说明

  • Exclude<string, '0000'>表示所有不等于'0000'的字符串类型,精准匹配"非'0000'"的状态码需求。
  • 这种写法保留了判别式联合类型的特性,TypeScript能通过statusCode的字面量类型准确推断对象其他属性,避免类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:35:23