Skip to content

Function cannot be contextually typed when its rest parameter type is tuple type with leading rest elements #45972

Open
@uhyo

Description

@uhyo

Bug Report

🔎 Search Terms

function rest arguments parameter tuple type leading middle rest elements

🕗 Version & Regression Information

4.2.3, 4.3.5, 4.4.2

  • I was unable to test this on prior versions because leading rest elements in tuple types were introduced in TS 4.2

⏯ Playground Link

Playground link with relevant code

💻 Code

type Func = (...args: [...strs: string[], num1: number, num2: number]) => void

// OK
const func: Func = () => {}
// Error:
// Type '(arg1: string | number) => void' is not assignable to type 'Func'.
//  Types of parameters 'arg1' and 'strs' are incompatible.
//    Type '[...strs: string[], num1: number, num2: number]' is not assignable to type '[arg1: string | number]'.
//      Source has 2 element(s) but target allows only 1.
const func1: Func = (arg1) => {}

// Error:
// Type '(arg2: string | number, arg3: string | number) => void' is not assignable to type 'Func'.
//   Types of parameters 'arg2' and 'strs' are incompatible.
//     Type '[...strs: string[], num1: number, num2: number]' is not assignable to type '[arg2: string | number, arg3: string | number]'.
//       Target allows only 2 element(s) but source may have more.
const func2: Func = (arg2, arg3) => {};

// Error:
// Type '(arg4: string | number, arg5: string | number, arg6: string | number) => void' is not assignable to type 'Func'.
//   Types of parameters 'arg4' and 'strs' are incompatible.
//     Type '[...strs: string[], num1: number, num2: number]' is not assignable to type '[arg4: string | number, arg5: string | number, arg6: string | number]'.
//       Target requires 3 element(s) but source may have fewer.
const func3: Func = (arg4, arg5, arg6) => {};

🙁 Actual behavior

Functions that have one or more arguments (func1, func2, func3) cannot be assigned to variables of type Func.

🙂 Expected behavior

No compiler errors and the types of arguments are inferred as:

  • arg1, arg2, arg3, arg4, arg5: string | number
  • arg6: string | number | undefined

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions