TypeScript无法从函数联合类型推断类型,该如何解决?
问题描述
给定以下TypeScript类型定义:
type HandlerA = (firstArg: string) => number; type HandlerB = (firstArg: string, secondArg: number) => string; type Handler = HandlerA | HandlerB
遇到的问题:
- 将函数
(a, b) => 'text'赋值给Handler类型的变量时,TypeScript能正常推断参数类型 - 但将函数
(a) => 10赋值给同类型变量时,参数a会被隐式推断为any,无法自动匹配HandlerA的参数要求 - 要求:不能通过
const testC: Handler = (a: string) => 10这种手动标注参数类型的方式解决
解决方案
方法1:使用泛型辅助函数(推荐)
创建一个泛型辅助函数,让TypeScript根据传入的函数反向推断类型,自动推导参数类型:
const createHandler = <T extends Handler>(handler: T) => handler; // 参数a自动被推断为string,返回值为number,匹配HandlerA const testB = createHandler((a) => 10);
原理:泛型T extends Handler会约束传入的函数必须符合Handler的子类型,TypeScript会根据函数的参数和返回值自动确定T的具体类型,从而完成参数类型的推断,不需要手动标注。
方法2:使用类型断言
直接通过类型断言将函数指定为Handler类型,也能触发参数类型推断:
const testB = ((a) => 10) as Handler;
注意:这种方式的类型检查强度略弱,如果函数不符合Handler类型,错误提示会不够直观,因此优先推荐辅助函数的方案。
内容的提问来源于stack exchange,提问作者Torsten
相关产品推荐
相关产品推荐

