如何在 TypeScript 中通用类型变量绑定?
How can I generically type variable bindings in TypeScript?
我有一个通用界面可供我使用:
CurriedFunction3<T1, T2, T3, R>: R
我想创建一个 const 绑定来填充其中一些类型参数。像这样:
type CurriedSorter<T> = CurriedFunction3<(obj: T) => any, string, T[], T[]>;
但是,当我尝试分配一个 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
绑定 sortFactory
应该是一个具有一个泛型类型参数的函数,这样使用:
sortFactory<MyType>(
prop('name'),
'DESC',
[{ name: 'foo' }, { name: 'bar' }]
) // returns `[{ name: 'bar' }, { name: 'foo' }]`
如何在 TypeScript 中通用类型变量绑定?有没有办法用 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;
}
我有一个通用界面可供我使用:
CurriedFunction3<T1, T2, T3, R>: R
我想创建一个 const 绑定来填充其中一些类型参数。像这样:
type CurriedSorter<T> = CurriedFunction3<(obj: T) => any, string, T[], T[]>;
但是,当我尝试分配一个 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
绑定 sortFactory
应该是一个具有一个泛型类型参数的函数,这样使用:
sortFactory<MyType>(
prop('name'),
'DESC',
[{ name: 'foo' }, { name: 'bar' }]
) // returns `[{ name: 'bar' }, { name: 'foo' }]`
如何在 TypeScript 中通用类型变量绑定?有没有办法用 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;
}