当功能包裹在课堂上时,通用会丢失
我正在编写一个小型实用程序,我需要能够使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论