all*_*loy 5 generics function type-alias typescript
我希望能够为一个非常通用的函数添加别名并指定部分通用参数,从而创建同一函数的不太通用的版本。像下面这样:
\n\nfunction veryGeneric<X, Y>(someParam: Y): { result: X } {\n // ...\n}\n\ntype LessGeneric = typeof veryGeneric<X, string>\nconst lessGeneric: LessGeneric = veryGeneric\nRun Code Online (Sandbox Code Playgroud)\n\n我希望该lessGeneric函数基本上键入为:
function lessGeneric<X>(someParam: string): { result: X } {\n // ...\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这有可能吗?
\n\n我知道我可以创建一个包装函数,但我宁愿不必再次指定参数类型(并且不必支付另一个函数调用的开销,即使它\xe2\x80\x99s很小,这将是一个额外的好处)。
\n\n这里\xe2\x80\x99s是我处理的真实例子\xe2\x80\x99m。给定一个函数声明(来自react-tracking),如下所示:
\n\ndeclare function track<T = {}, P = {}>(trackingInfo?: TrackingInfo<T, P>, options?: Options<Partial<T>>): Decorator\nRun Code Online (Sandbox Code Playgroud)\n\n我希望能够定义一个别名,指定trackingInfo参数\xe2\x80\x99s 类型,但保留P通用性。即我想要一个别名,\xe2\x80\x99s 本质上键入为:
interface ValidAnalyticsEntries {\n page: string\n action: string\n}\n\ndeclare function trackSpecificToOurAnalyticsSchema<P = {}>(trackingInfo?: TrackingInfo<ValidAnalyticsEntries, P>, options?: Options<Partial<ValidAnalyticsEntries>>): Decorator\nRun Code Online (Sandbox Code Playgroud)\n
要定义泛型类型别名,您可以定义一个描述函数签名的接口:
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)
| 归档时间: |
|
| 查看次数: |
2927 次 |
| 最近记录: |