Skip to content

Conversation

@ahejlsberg
Copy link
Member

This PR reverts #39281 and #39614 and instead implements the originally envisioned solution of giving higher priority to inferences made to [...T, X] than inferences made to [...T, X?] (because the latter speculates that the optional element is present). For example:

declare function ft<T extends unknown[]>(t1: [...T], t2: [...T, number?]): T;

ft([1, 2, 3], [1, 2, 3]);  // [1, 2, 3]
ft([1, 2], [1, 2, 3]);  // [1, 2]
ft(['a', 'b'], ['c', 'd']);  // ['a', 'b']
ft(['a', 'b'], ['c', 'd', 42]);  // ['a', 'b']

Fixes #39253.

@typescript-bot typescript-bot added the For Milestone Bug PRs that fix a bug with a specific milestone label Jul 24, 2020
@ahejlsberg ahejlsberg merged commit c5d21e7 into master Jul 24, 2020
@ahejlsberg ahejlsberg deleted the fixVariadicInference branch July 24, 2020 22:00
NoConstraints = 1 << 7, // Don't infer from constraints of instantiable types
AlwaysStrict = 1 << 8, // Always use strict rules for contravariant inferences
MaxValue = 1 << 9, // Seed for inference priority tracking
SpeculativeTuple = 1 << 1, // Speculative tuple inference
Copy link
Member

Choose a reason for hiding this comment

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

I think without the explanation, this is unclear.

else if (middleLength === 1 && elementFlags[startLength] & ElementFlags.Variadic) {
// Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
inferFromTypes(isTupleType(source) ? sliceTupleType(source, startLength, sourceEndLength) : createArrayType(sourceRestType!), elementTypes[startLength]);
// If target ends in optional element(s), make a lower priority a speculative inference.
Copy link
Member

Choose a reason for hiding this comment

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

If the documentation is going to be sparse on SpeculativeTuple, I think showing a concrete example here is worthwhile. Your explanation on the PR would be great.

@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

For Milestone Bug PRs that fix a bug with a specific milestone

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TS 4.0 Variadic tuple types: type inference with optional element not working as expected

5 participants