Skip to content

Infer return type of a function with provided argument types #26043

@int0h

Description

@int0h

I'm trying to create something similar to native ReturnType type. In comparison to the later, it should also consider generic types of arguments.

I guess the idea will be clear from the code below.

If it can be done now - I'd be happy to receive some links. Otherways it'd be great to know if there are any plans to cover that behavior. In case it could be achieved by another not-implemented feature I'll be glad for the link to an issue to be able to track its progress.

TypeScript Version: 2.9.2

Search Terms: infer function return type

Code

// it works with actual code:
function identity<T>(a: T) {
    return a;
}

const one = identity(1); // typeof one === 1 # everything is great

function call<A, R>(arg: A, fn: Func<A, R>): R {
    return fn(arg);
}

const two = call(2 as 2, i => i) // typeof two === 2 # everything is great

// but won't work with types
type Func<A, R> = (arg: A) => R;
// ReturnTypeByArg is inspired by `ReturnType` from TS 2.8.*
type ReturnTypeByArg<T, F extends Func<T, any>> = F extends Func<T, infer R> ? R : any;

type Identity = <T>(a: T) => T;
type Result = ReturnTypeByArg<4, Identity>; // Result === {} # not what I expect

Expected behavior:
I expect TS to be able to infer such return type

Actual behavior:
Return type is {}

Playground Link: link

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions