Skip to content

Conversation

@ahejlsberg
Copy link
Member

This PR improves contextual typing by generic rest parameters such that we can infer a tuple type from the function expression or arrow function being contextually typed while simultaneously assigning contextual parameter types to the function expression or arrow function. Consider:

declare function pipe<A extends any[], B, C>(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C;

let x1 = pipe(() => true, b => !b);  // () => boolean
let x2 = pipe(x => "hello", s => s.length);  // (x: any) => number
let x3 = pipe((x, y) => ({ x, y }), o => o.x === o.y);  // (x: any, y: any) => boolean
let x4 = pipe((x: number) => x * x, x => "" + x);  // (x: number) => string

In the examples above, the type inferred for A is [], [any], [any, any], and [number] respectively. Previously, in all but the last example we'd infer any[] for A.

// outer call expression. Effectively we just want a snapshot of whatever has been
// inferred for any outer call expression so far.
const instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
const instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node), InferenceFlags.NoDefault));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cloneTypeMapper call used to create the returnType mapper inside call resolution doesn't pass InferenceFlags.NoDefault with this change. Intentional?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's intentional. We only want the InferenceFlags.NoDefault behavior here (because we're transposing inferences from the outer call mapper and don't want an absence of inferences in the outer mapper to turn into what appears to be a concrete inference of the default).

@ahejlsberg ahejlsberg merged commit 7f5052b into master Feb 28, 2019
@ahejlsberg ahejlsberg deleted the contextualGenericRestParameter branch February 28, 2019 21:00
@microsoft microsoft locked as resolved and limited conversation to collaborators Oct 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants