当功能包裹在课堂上时,通用会丢失

发布于 2025-02-06 17:12:34 字数 987 浏览 2 评论 0原文

我正在编写一个小型实用程序,我需要能够使用generics表达功能组成:

function compose<A, B, C>(f: (a: A) => B, g: (b: B) => C): (a: A) => C {
    return a => g(f(a));
}

在这种情况下,TS似乎能够“通过”类型变量并正确地推断出结果类型:

const good = compose(<T>(t: T) => t, <T>(t: T) => t); // <T>(a: T) => T

我的下一步涉及包装这些功能在课堂中的功能,因此至少我需要返回包装器:

class Wrapper<T> {
    constructor(public readonly value: T) { }
}

function wrapCompose<A, B, C>(f: (a: A) => B, g: (b: B) => C): Wrapper<(a: A) => C> {
    return new Wrapper(compose(f, g));
}

wrapCompose的类型与compose相同,只是将结果包装在包装器。但是现在这还不正确。

const bad = wrapCompose(<T>(t: T) => t, <T>(t: T) => t); // Wrapper<(a: unknown) => unknown>

为什么类型推理在这里破裂? 包装器根本不做任何事情,因此我希望使用完全相同的规则键入其值,就像它是一个平均值一样。有没有办法包裹我的功能结果以使TS正确地渗透结果?

I'm writing a small utility for which I need to be able to express function composition using generics:

function compose<A, B, C>(f: (a: A) => B, g: (b: B) => C): (a: A) => C {
    return a => g(f(a));
}

In this case, TS seems to be able to "pass through" the type variables and infer the resulting type correctly:

const good = compose(<T>(t: T) => t, <T>(t: T) => t); // <T>(a: T) => T

My next step involves wrapping these functions in a class, so at a minimum, my composition function needs to return a wrapper:

class Wrapper<T> {
    constructor(public readonly value: T) { }
}

function wrapCompose<A, B, C>(f: (a: A) => B, g: (b: B) => C): Wrapper<(a: A) => C> {
    return new Wrapper(compose(f, g));
}

The type of wrapCompose is identical to compose, except that it wraps the result in a Wrapper. But now this is not typed correctly.

const bad = wrapCompose(<T>(t: T) => t, <T>(t: T) => t); // Wrapper<(a: unknown) => unknown>

Why is type inference breaking here? Wrapper doesn't do anything at all, so I'd expect its value to be typed using the exact same rules as if it was a plain value. Is there a way to wrap the result of my function such that TS correctly infers the result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文