Closed
Description
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[]