如何正确重载函数适配特定类型T?解决隐式any类型问题
解决TypeScript函数重载中参数隐式any的问题
问题场景
原始函数如下:
function test(input) { if (typeof input === 'number') { return 'a' } else { return input } }
为该函数添加类型定义时,尝试了函数重载方案:
function test<T extends number>(input: T): string; function test<T>(input: T): T; function test(input) { if (typeof input === 'number') { return 'a' } else { return input } } const a = [test('2'), test(2), test(null), test(true)] as const // ^? a: readonly ['2', string, null, true] const b = [test<string>('2'), test<boolean>(true)] as const // ^? b: readonly [string, boolean]
但此时实现函数的参数input出现**“隐式具有any类型”**的类型检查提示,需要在保持类型推断正确性的前提下解决该问题。
原因分析
TypeScript开启严格类型检查(strict: true)时,会禁止未显式标注类型的参数隐式推断为any。当前实现函数的input未指定类型,因此触发了该提示。
解决方案
给实现函数的参数和返回值添加兼容所有重载签名的显式类型。由于函数逻辑是“输入数字返回字符串,输入其他类型返回原类型”,可以用unknown作为参数和返回值的类型——它能兼容所有可能的输入输出,同时完全匹配函数的实际逻辑:
function test<T extends number>(input: T): string; function test<T>(input: T): T; function test(input: unknown): unknown { if (typeof input === 'number') { return 'a' } else { return input } }
验证效果
修改后,原有的类型推断依然保持正确:
const a = [test('2'), test(2), test(null), test(true)] as const的类型仍为readonly ['2', string, null, true]const b = [test<string>('2'), test<boolean>(true)] as const的类型仍为readonly [string, boolean]
同时,TypeScript不再提示“隐式具有any类型”的错误。
内容的提问来源于stack exchange,提问作者skyboyer
相关产品推荐
相关产品推荐

