如何使TypeScript函数返回类型根据输入枚举参数动态确定?
解决TypeScript函数输入输出类型关联问题
你遇到的问题是TypeScript无法根据传入的Format枚举值自动推断函数的精确返回类型,导致b被推断为number | string。可以通过以下两种方式实现输入与返回类型的精准关联:
方法一:函数重载
函数重载允许你为不同的参数类型定义对应的返回类型,TypeScript会根据传入的参数匹配对应的重载签名,从而推断出正确的返回类型:
enum Format{ hex, integer } // 定义重载签名,明确参数与返回类型的对应关系 function fun(a: Format.hex): string; function fun(a: Format.integer): number; // 函数实现(无需指定返回类型,TypeScript会自动匹配重载) function fun(a: Format) { const k = Math.floor(Math.random()*100) if (a === Format.hex) { return k.toString(16) } else { return k } } const b = fun(Format.hex) // 类型自动推断为string const c = fun(Format.integer) // 类型自动推断为number
这种方式写法直观,适合参数与返回类型映射关系简单的场景。
方法二:泛型结合条件类型
通过泛型捕获传入的具体枚举值,再用条件类型映射对应的返回类型,实现更灵活的类型关联:
enum Format{ hex, integer } // 定义条件类型,根据Format枚举值映射返回类型 type ReturnTypeForFormat<T extends Format> = T extends Format.hex ? string : number; function fun<T extends Format>(a: T): ReturnTypeForFormat<T> { const k = Math.floor(Math.random()*100) if (a === Format.hex) { // 用类型断言告诉编译器返回值符合条件类型 return k.toString(16) as ReturnTypeForFormat<T> } else { return k as ReturnTypeForFormat<T> } } const b = fun(Format.hex) // 类型自动推断为string const c = fun(Format.integer) // 类型自动推断为number
这种方式更适合复杂的类型映射场景,当后续需要扩展Format枚举时,只需修改条件类型即可。
内容的提问来源于stack exchange,提问作者sev
相关产品推荐
相关产品推荐

