Maxime Dupré
Maxime Dupré

Reputation: 5737

Is it possible to use the return type of a function as the type of a variable?

Let say I have this function:

let getData = () => {
    return {
        name: 'John',
        age: 2,
        isAsian: true
    }
}

How do I say (if even possible) that a variable's type is the return type of getData, without affecting it to getData?

For example, I'm looking for something like:

var data: getData

Of course this does not work, as the type would be the function and not the return value of the function. (Edit: Actually it would just give the error: Cannot find name 'getData')

var data = getData() would work; the type of data would be inferred to {name: string, age: number, isAsian: boolean}, but this is not a solution for me.

There is a discussion here that might be related to my issue: Obtaining the return type of a function

However, it does not seem to be the solution I'm looking for. First I can't use Typescript 2.8 yet (I'm using angular and the CLI won't let me). I think that the alternative, just like the main solution of this SO question is not useful to me, because I'm looking to use the return type of my function dynamically.

Upvotes: 0

Views: 211

Answers (2)

artem
artem

Reputation: 51629

Here is another solution for pre-2.8 compiler. It still involves one extra function and one dummy variable, but it does not have a call to getData() in the code:

let getData = () => {
    return {
        name: 'John',
        age: 2,
        isAsian: true
    }
}


function getReturnType<R>(f: (...args: any[]) => R): { returnType: R } {
    return null!;
}

// dummy variable, used for retrieving getData return type only
let dataType = getReturnType(getData);

var data: typeof dataType.returnType; // var data: { name: string; age: number; isAsian: boolean; }

Upvotes: 3

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

As of TypeScript 2.9 (sorry), you can use the ReturnType type:

let getData = () => {
    return {
        name: 'John',
        age: 2,
        isAsian: true
    }
}

let p: ReturnType<typeof getData>;
p.name; // string

There are workarounds you can use prior to 2.9 but they're not very good. One way is:

let fake = (false as any) && getData();
let p: typeof fake;

Upvotes: 3

Related Questions