TypeScript 是否允许类型别名来指定泛型?

all*_*loy 5 generics function type-alias typescript

我希望能够为一个非常通用的函数添加别名并指定部分通用参数,从而创建同一函数的不太通用的版本。像下面这样:

\n\n
function veryGeneric<X, Y>(someParam: Y): { result: X } {\n  // ...\n}\n\ntype LessGeneric = typeof veryGeneric<X, string>\nconst lessGeneric: LessGeneric = veryGeneric\n
Run Code Online (Sandbox Code Playgroud)\n\n

我希望该lessGeneric函数基本上键入为:

\n\n
function lessGeneric<X>(someParam: string): { result: X } {\n  // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这有可能吗?

\n\n

我知道我可以创建一个包装函数,但我宁愿不必再次指定参数类型(并且不必支付另一个函数调用的开销,即使它\xe2\x80\x99s很小,这将是一个额外的好处)。

\n\n
\n\n

这里\xe2\x80\x99s是我处理的真实例子\xe2\x80\x99m。给定一个函数声明(来自react-tracking),如下所示:

\n\n
declare function track<T = {}, P = {}>(trackingInfo?: TrackingInfo<T, P>, options?: Options<Partial<T>>): Decorator\n
Run Code Online (Sandbox Code Playgroud)\n\n

我希望能够定义一个别名,指定trackingInfo参数\xe2\x80\x99s 类型,但保留P通用性。即我想要一个别名,\xe2\x80\x99s 本质上键入为:

\n\n
interface ValidAnalyticsEntries {\n  page: string\n  action: string\n}\n\ndeclare function trackSpecificToOurAnalyticsSchema<P = {}>(trackingInfo?: TrackingInfo<ValidAnalyticsEntries, P>, options?: Options<Partial<ValidAnalyticsEntries>>): Decorator\n
Run Code Online (Sandbox Code Playgroud)\n

Ale*_* L. 4

要定义泛型类型别名,您可以定义一个描述函数签名的接口:

interface VeryGeneric<X, Y> {
    (someParam: Y): { result: X };
}

type Foo = { foo: number };
type LessGeneric<X = Foo> = VeryGeneric<X, string>;

const lessGeneric: LessGeneric = veryGeneric;
Run Code Online (Sandbox Code Playgroud)