我有以下功能:
function test(): number {
return 42;
}
我可以通过typeof获得函数的类型:
type t = typeof test;
这里t是()=> number。
是否有方法获取函数的返回类型?我希望t是number而不是()=> number。
我有以下功能:
function test(): number {
return 42;
}
我可以通过typeof获得函数的类型:
type t = typeof test;
这里t是()=> number。
是否有方法获取函数的返回类型?我希望t是number而不是()=> number。
当前回答
编辑:这是不需要与TS 2.8更多!>给出返回类型。见已接受答案。
我使用的一些以前答案的变体,它在strictNullChecks中工作,并隐藏了推理体操:
function getReturnType<R>(fn: (...args: any[]) => R): R {
return {} as R;
}
用法:
function foo() {
return {
name: "",
bar(s: string) { // doesn't have to be shorthand, could be `bar: barFn`
return 123;
}
}
}
const _fooReturnType = getReturnType(foo);
export type Foo = typeof _fooReturnType; // type Foo = { name: string; bar(s: string): number; }
它调用getReturnType函数,但不调用原始函数。你可以使用(false为true) && getReturnType(foo)来防止getReturnType调用,但在我看来,这只会让它更混乱。
我只是使用这个方法和一些regexp find/replace来迁移旧的Angular 1。x项目有大约1500个工厂函数是这样写的,最初是在JS中,并添加了Foo等类型到所有用途…你会发现令人惊讶的坏代码。:)
其他回答
我想出了以下方法,看起来效果不错:
function returnType<A, B, Z>(fn: (a: A, b: B) => Z): Z
function returnType<A, Z>(fn: (a: A) => Z): Z
function returnType<Z>(fn: () => Z): Z
function returnType(): any {
throw "Nooooo"
}
function complicated(value: number): { kind: 'complicated', value: number } {
return { kind: 'complicated', value: value }
}
const dummy = (false as true) && returnType(complicated)
type Z = typeof dummy
没有办法做到这一点(请参阅https://github.com/Microsoft/TypeScript/issues/6606以获取添加此功能的工作项跟踪)。
一个常见的解决方法是这样写:
var dummy = false && test();
type t2 = typeof dummy;
编辑:这是不需要与TS 2.8更多!>给出返回类型。见已接受答案。
我使用的一些以前答案的变体,它在strictNullChecks中工作,并隐藏了推理体操:
function getReturnType<R>(fn: (...args: any[]) => R): R {
return {} as R;
}
用法:
function foo() {
return {
name: "",
bar(s: string) { // doesn't have to be shorthand, could be `bar: barFn`
return 123;
}
}
}
const _fooReturnType = getReturnType(foo);
export type Foo = typeof _fooReturnType; // type Foo = { name: string; bar(s: string): number; }
它调用getReturnType函数,但不调用原始函数。你可以使用(false为true) && getReturnType(foo)来防止getReturnType调用,但在我看来,这只会让它更混乱。
我只是使用这个方法和一些regexp find/replace来迁移旧的Angular 1。x项目有大约1500个工厂函数是这样写的,最初是在JS中,并添加了Foo等类型到所有用途…你会发现令人惊讶的坏代码。:)
在TypeScript 2.8中最简单的方法是:
const foo = (): FooReturnType => {
}
type returnType = ReturnType<typeof foo>;
// returnType = FooReturnType
下面的代码无需执行函数即可工作。它来自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;