我有一个通用接口(interface)可供我使用:
CurriedFunction3<T1, T2, T3, R>: R
我想创建一个 const 绑定(bind)来填充其中一些类型参数。像这样:
type CurriedSorter<T> = CurriedFunction3<(obj: T) => any, string, T[], T[]>;
但是,当我尝试分配绑定(bind)此类型的 const
时,出现错误:
type CurriedSorter<T> = CurriedFunction3<(obj: T) => any, string, T[], T[]>;
const sortFactory: CurriedSorter = uncurryN(3, flip(compose(
unapply(sortWith),
uncurryN(2, ifElse(
compose(equals('DESC'), toUpper),
always(descend),
always(ascend),
)),
)));
Generic type
CurriedSorter
requires 1 type argument(s).
const
绑定(bind) sortFactory
应该是一个具有一个泛型类型参数的函数,这样使用:
sortFactory<MyType>(
prop('name'),
'DESC',
[{ name: 'foo' }, { name: 'bar' }]
) // returns `[{ name: 'bar' }, { name: 'foo' }]`
我如何在 TypeScript 中通用地键入变量绑定(bind)?有没有办法用 TypeScript 做到这一点?
最佳答案
您不能在变量声明的类型中使用裸T
,因为T
可能会通过属性泄漏出值。但是,您可以将通用调用签名 作为变量类型的一部分。这是一个独立的示例,因为我不知道您将 uncurryN
、unapply
等定义为:
type CurriedFunction3<T1, T2, T3, R> = (a: T1, b: T2, c: T3) => R;
type CurriedSorter<T> = CurriedFunction3<(obj: T) => any, string, T[], T[]>;
type CurriedSorterValue = {
<T>(a: (obj: T) => any, b: string, c: T[]): T[];
}
const sortFactory: CurriedSorterValue = function (a, b, c) {
return c;
}
关于javascript - 如何在 TypeScript 中通用类型变量绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50178758/