Typescript 从默认值推断泛型类型

标签 typescript

考虑以下函数。

public static convert<T, U>(t: T, conversion: ((toutput: T) => U) = ((t) => t)) { 
    return conversion(t);
}

Typescript 目前提示转换函数返回的 toutput 参数,这是默认参数:

Type 'T' is not assignable to type 'U'. 'U' could be instantiated with an arbitrary type which could be unrelated to 'T'.

我试图让 IDE 认识到,在给定默认参数的情况下,T 与 U 相同。

我的用例如下:

convert(1) // returns 1
convert(1, x => ({x})) // returns an object with { x : 1 }

有没有人知道有什么方法可以让编译器安静下来并能够正确创建上面的这个函数?

最佳答案

我认为你可以通过重载来实现这一点:

public static function convert<T>(t: T): T;
public static function convert<T, U>(t: T, conversion: (t: T) => U): U;
public static function convert<T, U>(t: T, conversion?: (t: T) => U) {
    return conversion ? conversion(t) : t;
}

..

const foo = convert(1)             // inferred type 1
const bar = convert(1, x => ({x})) // inferred type { x : number }

1 被扩展为 number,因为隐式文字类型在返回值的上下文中被扩展(例如 x => ({x})),这又导致 T 被推断为 number。您可以通过显式键入第一个参数来避免这种情况:

const bar = convert(1 as 1, x => ({x})) // inferred type { x: 1 }

关于Typescript 从默认值推断泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169365/

相关文章:

typescript - Vue 3 : Setup Script, TS问题: "An import declaration can only be used in a namespace or module."

typescript 通用 promise 返回类型

xml-documentation - TypeScript 中是否已经支持 XML 文档?

reactjs - Redux TS 通用类型 'Dispatch<S>' 需要 1 个类型参数

azure - 将 TypeScript 部署到 Azure - 您的项目文件使用不同版本的 TypeScript 编译器

function - TypeScript 中错误抛出函数的签名

javascript - Typescript 错误和展开运算符是由 ...props 引起的?

Angular 5从子组件更新父组件值

angular - 后台图片不显示

javascript - 如何跨多个 React Redux 组件使用 requestAnimationFrame 实现游戏循环?