microsoft/TypeScript

Type query for a result of a function call

Strate opened this issue · 11 comments

Is it possible to use typeof type query operator to get function's return type?

Seems that no. It would be great to do something like:

declare var do: (arg: string) => number

let a: typeof do // a now has (arg: string) => number type
let b: typeof do() // b now has number type

This comment is related: #2710 (comment)

Duplicate of #4233?

I have also encountered this problem many times.

What would be the inferred type in the following situation?

function fn<a>(value: a) : { value: a; } { return { value: value }; }
let a: typeof fn;

If the answer is {value: {}} (assuming the current state of affairs) then such feature is useless.

@DanielRosenwasser, how feasible is it to allow variables to hold unresolved its own declared (not from the context) type parameters?

Might be related #5959

I think answer should be an error about required type argument, and developer should write

let a: typeof fn<number>()

to get {value: number}

@Strate
this is pure syntax sugar over

let b = fn<number>();
let a : typeof b;

if this is what you are looking for then it might be better phrased as "Type query for a result of a function call"

You are right, I'm gonna to change the caption :)

I'm wondering how this would handle overloaded functions? I guess one must pass in the type of the arguments to let it overload correctly the return type.

function f(a: string): string;
function f(a: string, b: number): boolean;
function f(a: string, b?: string | number, c?: string): boolean | string {
    return true;
}

typeof f(string, number) // boolean

Isn't ellipses ... a better syntax for not overloaded functions? Because only f() (no arguments) doesn't corresponds to the function signature f(a: string) (with one argument).

function f(a: string): boolean;
typeof f(...) // boolean

@tinganho #4233 takes care of that - just use any valid expression - like typeof f("", 0)

Proposal + implementation that covers this: #6606