简体   繁体   English

打字稿中的映射函数类型可能吗?

[英]Possible for mapped function types in typescript?

Say I have a function type in typescript假设我在打字稿中有一个函数类型

interface ParseFn {
  (param: string): number;
}

Is there a way to map function types in TypeScript?有没有办法在 TypeScript 中映射函数类型? Can I do something like我可以做类似的事情吗

type Async<T> = {
  [P in keyof T]: Promise<T[P]>;
}

const myAsyncNumParser: Async<ParseFn> = ...

?

Mapped types in TypeScript completely ignore call and construct signatures, so they won't do what you want. TypeScript 中的映射类型完全忽略调用和构造签名,因此它们不会执行您想要的操作。 Instead, you can use type inference in conditional types introduced in TypeScript 2.8.相反,您可以在 TypeScript 2.8 中引入的条件类型中使用类型推断 Assuming what you want is to take a function type T and return a new function type which takes the same parameters but whose return type is wrapped in Promise<> , you can do it like this:假设你想要的是采用一个函数类型T并返回一个新的函数类型,它采用相同的参数但其返回类型包装在Promise<>中,你可以这样做:

type Async<T extends (...args: any) => any> =
    T extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : never;
type AsyncParseFn = Async<ParseFn>;
// type AsyncParseFn = (param: string) => Promise<number>

There are also predefined utility types called Parameters<T> and ReturnType<T> that use such conditional types to get the parameter tuple and return type of a function type.还有称为Parameters<T>ReturnType<T>的预定义实用程序类型,它们使用此类条件类型来获取函数类型的参数元组和返回类型。 You could use those, instead, if you prefer:如果您愿意,可以使用它们:

type Async2<T extends (...args: any) => any> =
    (...args: Parameters<T>) => Promise<ReturnType<T>>;
type Async2ParseFn = Async<ParseFn>;
// type Async2ParseFn = (param: string) => Promise<number>

Either way should work.无论哪种方式都应该工作。 Okay, hope that helps;好的,希望有所帮助; good luck!祝你好运!

Playground link to code 游乐场代码链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM