Skip to content

Suggestion: Enable inferring the result type of a generic function based on the context in which it is used #3423

@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

It's a very common situation in our code when we wish TypeScript could infer the result type of a function with a generic result based on the context in which that function is used. Here are a couple of use cases to support the feature request:

Case 1: Generic fail function (for being able to throw from an expression)

function fail<r>(message: string) : r { throw new Error(message); }
function id<a>(value: a) : a { return value; }
function withFew<a, r>(values: a[], haveFew: (values: a[]) => r, haveNone: (reason: string) => r) : r {
    return values.length > 0 ? haveFew(values) : haveNone('Array is empty.');
}
var values = Math.random() > 0.5 ? ['a', 'b', 'c'] : [];
var few = withFew(values, id, fail); // <-- actual result is {}, expected is string[]

Case 2: Empty container constructors:

function toArrayOf<a>() : a[] { return []; }
function id<a>(value: a) : a { return value; }
function withSome<a>(valueOpt: a, haveSome: (value: a) => r, haveNone: (reason: string)  => r) : r {
    return valueOpt != null ? haveSome(valueOpt) : haveNone('Value is unspecified.');
}
var valuesOpt = Math.random() > 0.5 ? ['a', 'b', 'c'] : null;
var values = withSome(valueOpt, id, toArrayOf); // <-- actual result is {}, expected is string[]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions