通过这个例子:
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
将返回函数。
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
助手基本上与ReturnType
TypeScript 中存在的助手相匹配。
归档时间: |
|
查看次数: |
1986 次 |
最近记录: |