Microsoft/TypeScript
View on GitHubShorter tuple inference gets picked over longer inference when both come from rests
Open
#57,981 opened on Mar 28, 2024
Domain: check: Type InferenceHelp WantedPossible Improvement
Repository metrics
- Stars
- (48,455 stars)
- PR merge metrics
- (Avg merge 6d 17h) (9 merged PRs in 30d)
Description
🔎 Search Terms
inference contravariant covariance rest shorter longer tuples
🕗 Version & Regression Information
- This is the behavior in every version I tried
⏯ Playground Link
💻 Code
declare function fn<A extends readonly unknown[]>(
arg: (...args: A) => void,
...args: A
): A;
const inferred = fn((a: number) => {}, 1, 2); // Expected 2 arguments, but got 3.(2554)
// ^? const inferred: [a: number]
const inferred2 = fn((a: number, b?: number) => {}, 1); // ok
// ^? const inferred2: [number]
const inferred3 = fn((a: number, b?: number) => {}, 1 as const); // ok
// ^? const inferred3: [1]
🙁 Actual behavior
inferred is [a: number] and the function call fails
🙂 Expected behavior
inferred should be [number, number] and the function call should succeed.
Additional information about the issue
Based on inferred2 and inferred3 we can see that the covariant inference is preferred in a situation like this. The problem is the .length mismatch between those 2 candidates but since the contravariant candidate comes from a rest position it should be ignored when comparing those 2 candidates and the covariant inference should be preferred