以此为例:
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,
};
我想提取type
该函数将返回,因此我可以重用该类型。我想不出有什么办法可以得到它。上面的方法不起作用。typeof getValue
将返回该函数。
流有一个$Call
实用程序类型,可以获取函数的返回类型:
type TheReturnType = $Call<typeof getValue>
但是,如果您的函数接受参数,您还需要为这些参数提供类型:
type TimeoutType = $Call<typeof setTimeout, () => void, number>
如果这看起来不方便,你可以写一个ReturnType
可以跳过参数需求的帮助器:
type ReturnType<F> =
$PropertyType<$ObjMap<{ x: F }, <R>(f: (...any) => R) => R>, 'x'>
让我们使用这个:
type TheReturnType = ReturnType<typeof setTimeout>
This ReturnType
助手基本上匹配ReturnType
TypeScript 中存在助手。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)