Contextual generic function types by ahejlsberg · Pull Request #16305 · microsoft/TypeScript (original) (raw)
With this PR we do not erase the type parameters of contextual generic function types. Instead, the type parameters are allowed to propagate into the contextually typed expression. For example:
const f: (a: A) => A = a => a; // Type of a is A
Previously, contextual generic function types were ignored and a
would therefore have been of type any
.
This PR also expands upon #16072 to permit the contextual type of a generic function to itself be a generic function type. For example:
const arrayMap = <T, U>(f: (x: T) => U) => (a: T[]) => a.map(f); const arrayFilter = (f: (x: T) => boolean) => (a: T[]) => a.filter(f);
const f1: (a: string[]) => number[] = arrayMap(x => x.length); // x: string const f2: (a: A[]) => A[][] = arrayMap(x => [x]); // x: A const f3: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); // value: A const f4: (a: string[]) => string[] = arrayFilter(x => x.length > 10); // x: string const f5: <T extends { value: number }>(a: T[]) => T[] = arrayFilter(x => x.value > 10); // x: T
Fixes #16293.