Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve contextual typing by generic rest parameters #30114

Merged
merged 4 commits into from
Feb 28, 2019

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.

@@ -20018,7 +20018,7 @@ namespace ts {
// We clone the contextual mapper to avoid disturbing a resolution in progress for an
// 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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants