返回AsyncFunction的Typescript函数的适当返回类型是什么?

时间:2018-12-21 16:52:46

标签: typescript async-await

此代码应该可以正常运行...

let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;

export function createJsFunction(event: string, body: string[]): any {
  return new AsyncFunction(body.join("\n") + "\n//# sourceURL=" + event);
}

..但是createJsFunction的“ any”返回值使我不高兴。什么是合适的返回类型?

如果我使用常规的Function类型,显然是Function ...但是使用AsyncFunction则会得到Cannot find name 'AsyncFunction'

1 个答案:

答案 0 :(得分:2)

首先,我们可以稍微缩小AsyncFunction的类型。内置的类型说它是any,但我们知道它实际上是FunctionConstructor

let AsyncFunction: FunctionConstructor = Object.getPrototypeOf(async function () {}).constructor;

现在,我们可以像使用标准Function构造函数那样使用它。

const createJsFunction = new AsyncFunction('event', 'body', `
  await body.join('\\n') + '\\n//# sourceURL=' + event
`);

(请注意模板字符串中的双反斜杠。)

这有效,但是createJsFunction的推断类型仅为Function。这是因为类型系统无法在编译时知道结果是什么。

如果我们知道实际的签名是什么,我们可以使用类型断言(在这里:as (event: string, body: string[]) => Promise<string>)告诉TypeScript:

const createJsFunction = new AsyncFunction('event', 'body', `
  body.join('\\n') + '\\n//# sourceURL=' + event
`) as (event: string, body: string[]) => Promise<string>;

正如您在评论中提到的那样,使用AsyncFunction构造函数的好处是您可以await在正在构造的函数中。

const createJsFunction = new AsyncFunction('event', 'body', `
  await body.join('\\n') + '\\n//# sourceURL=' + event
`) as (event: string, body: string[]) => Promise<void>;
相关问题