rid*_*rid 63 typescript typescript1.8
我有以下功能:
function test(): number {
return 42;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法获取函数的类型typeof:
type t = typeof test;
Run Code Online (Sandbox Code Playgroud)
在这里,t将是() => number.
有没有办法获得函数的返回类型?我想t是number不是() => number.
the*_*rns 102
编辑
从TypeScript 2.8开始,这正式可行ReturnType<T>.
type T10 = ReturnType<() => string>; // string
type T11 = ReturnType<(s: string) => void>; // void
type T12 = ReturnType<(<T>() => T)>; // {}
type T13 = ReturnType<(<T extends U, U extends number[]>() => T)>; // number[]
Run Code Online (Sandbox Code Playgroud)
详情请见此处.
TypeScript太棒了!
老派黑客
不幸的是,Ryan的答案不再适用了.但是我用黑客修改了它,我对此感到非常高兴.看吧:
const fnReturnType = (false as true) && fn();
Run Code Online (Sandbox Code Playgroud)
它通过将false转换为true的文字值来工作,因此类型系统认为返回值是函数的类型,但是当您实际运行代码时,它会在false时短路.
TypeScript是最好的.:d
小智 24
TypeScript 2.8中最简单的方法:
const foo = (): FooReturnType => {
}
type returnType = ReturnType<typeof foo>;
// returnType = FooReturnType
Run Code Online (Sandbox Code Playgroud)
小智 14
使用内置ReturnType:
type SomeType = ReturnType<typeof SomeFunc>
Run Code Online (Sandbox Code Playgroud)
ReturnType扩展到:
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
Run Code Online (Sandbox Code Playgroud)
下面的代码无需执行函数即可工作。它来自 react-redux-typescript 库(https://github.com/alexzywiak/react-redux-typescript/blob/master/utils/redux/typeUtils.ts)
interface Func<T> {
([...args]: any, args2?: any): T;
}
export function returnType<T>(func: Func<T>) {
return {} as T;
}
function mapDispatchToProps(dispatch: RootDispatch, props:OwnProps) {
return {
onFinished() {
dispatch(action(props.id));
}
}
}
const dispatchGeneric = returnType(mapDispatchToProps);
type DispatchProps = typeof dispatchGeneric;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22163 次 |
| 最近记录: |