如何在流中获取函数的返回类型?

Lau*_*ing 6 flowtype

通过这个例子:

const myObj = {
    test: true,
};

type MyType = typeof myObj;

const getValue = (): MyType => {
    return myObj;
};

// how to do this??
type TheReturnType = getValue;

const nextObj: TheReturnType = {
    test: false,
};
Run Code Online (Sandbox Code Playgroud)

我想提取type函数将返回的 ,以便我可以重用该类型。我想不出办法得到它。以上是行不通的。typeof getValue将返回函数。

Wil*_*son 6

Flow 有一个$Call实用程序类型,它可以获取函数的返回类型:

type TheReturnType = $Call<typeof getValue>
Run Code Online (Sandbox Code Playgroud)

但是,如果您的函数接受参数,则还需要为这些参数提供类型:

type TimeoutType = $Call<typeof setTimeout, () => void, number>
Run Code Online (Sandbox Code Playgroud)

如果这看起来不方便,您可以编写一个ReturnType可以跳过参数需求的帮助程序:

type ReturnType<F> =
  $PropertyType<$ObjMap<{ x: F }, <R>(f: (...any) => R) => R>, 'x'>
Run Code Online (Sandbox Code Playgroud)

让我们用这个:

type TheReturnType = ReturnType<typeof setTimeout>
Run Code Online (Sandbox Code Playgroud)

这个ReturnType助手基本上与ReturnTypeTypeScript 中存在的助手相匹配。