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

如何更优雅地收窄TypeScript类型?无需双return实现

实现单return的类型格式化函数

先明确输入和输出的类型定义(方便理解场景):

// 输入类型
type ApiSuccessType = {
  isError: false;
  data: string;
};

type ApiErrorType = {
  isError: true;
  message: string;
  timestamp: number;
};

type ApiResponse = ApiErrorType | ApiSuccessType;

// 输出类型
type MySuccessType = {
  success: true;
  content: string;
};

type MyErrorType = {
  success: false;
  errorMsg: string;
  time: number;
};

type MyResponse = MySuccessType | MyErrorType;

单return实现方案

利用TypeScript的类型窄化特性,结合三元条件表达式即可实现优雅的单return写法:

function betterFormatter(response: ApiResponse): MyResponse {
  return response.isError 
    ? {
        success: false,
        errorMsg: response.message,
        time: response.timestamp
      }
    : {
        success: true,
        content: response.data
      };
}

原理说明

当通过response.isError判断时,TypeScript会自动将response的类型在分支中窄化:

  • 分支为true时,response被识别为ApiErrorType,可安全访问timestamp和message字段
  • 分支为false时,response被识别为ApiSuccessType,可安全访问data字段

返回的两个分支对象分别完全匹配MyErrorType和MySuccessType的结构,TypeScript会自动推断返回值为MyResponse联合类型,下游代码可以通过success字段判断具体类型,实现类型安全的分支处理。

如果遇到更复杂的字段映射场景,可拆分小型转换辅助函数,但当前场景下三元表达式已足够简洁清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:55:29