TypeScript中T | undefined场景下函数重载的简化写法问询
TypeScript中
T | undefined类型的函数重载及简化方案 一、T | undefined类型的函数重载语法
当参数类型为T | undefined时,函数重载的常规写法是拆分两种具体场景的签名,再搭配覆盖所有情况的实现签名:
- 第一个重载:参数为
T时,返回对应的非undefined类型 - 第二个重载:参数为
undefined时,返回undefined - 最后一个实现签名:参数和返回值都用联合类型,作为函数实际逻辑的类型兜底
就像你给出的示例代码那样,前两个重载明确了不同输入对应的精确输出,第三个实现签名则是函数逻辑的类型声明。
二、简化注解的方案:泛型+条件类型
要避免写多个重载签名,可以用泛型结合条件类型实现输入输出的精确类型映射,只需要一个重载签名就能达到同样的效果:
import { formatISO } from "date-fns"; export function stringifyDate<T extends Date | undefined>(unformattedDate: T): T extends Date ? string : undefined; export function stringifyDate(unformattedDate: Date | undefined): string | undefined { return unformattedDate ? formatISO(unformattedDate, { representation: "date" }) : undefined; }
这种写法下,TypeScript会自动根据传入的参数类型推断返回值:
- 传入
Date类型参数时,返回类型被推断为string - 传入
undefined时,返回类型被推断为undefined
完全等价于你原来的多重载写法,但代码更简洁。
内容的提问来源于stack exchange,提问作者Johan Lindskogen
相关产品推荐
相关产品推荐

