15
// Works fine in 4.3.5, not in 4.4.2

type ArgsTupleUnion<T> =
  | [obj: T, x: (arg: T) => void]
  | [y: (arg: number) => void];

function f<T>(...args: ArgsTupleUnion<T>) {}

f({ k: 15 }, (arg) => { // 4.3.5: arg is {k: number}, 4.4.2: arg is 'any'
  console.log(arg.k);
});

f((a: number) => {});


type ArgsTuple<T> =
  | [obj: T, x: (arg: T) => void]
  // | [y: (arg: number) => void];

function f2<T>(...args: ArgsTuple<T>) {}

f2({ k: 15 }, (arg) => { // Both 4.3.5 and 4.4.2: arg is {k: number}
  console.log(arg.k);
});

Here's the code on TS Playground. I'm not sure which change has made this stop working but it's preventing me from upgrading to 4.4. Anyone else who has run into this or has an idea for a workaround?

4
  • I have a similar (but not the same) problem here stackoverflow.com/questions/69254779/… tsplayground: tsplay.dev/Na0Mow . I think it worth creating and issue and wait for official explanation Commented Sep 21, 2021 at 7:54
  • 1
    Maybe it has something to do with the new Control Flow Analysis. However for a quick fix you could use [y: (arg: T) => void] Commented Sep 21, 2021 at 7:55
  • @captain-yossarian It does look similar but in your example changing to 4.3.5 doesn't seem to make a difference so I'd classify it as a separate issue.
    – JH-
    Commented Sep 21, 2021 at 8:18
  • @MuratKaragöz Thanks for the suggestion, seems like that will have to do for now.
    – JH-
    Commented Sep 21, 2021 at 8:19

1 Answer 1

0

A possible work around would be to use functional overload

It seems that typescript is opting in for the more specific type number rather than tracking the number of elements in a given array.

type ArgsTuple<T> = [obj: T, x: (arg: T) => void];
type NumArrFun = [y: (arg: number) => void];

type ArgsTupleUnion<T> =
  | ArgsTuple<T>
  | NumArrFun;

function f<T>(...args: ArgsTuple<T>): void
function f<T>(...args: NumArrFun): void
function f<T>(...args: ArgsTupleUnion<T>) {}

f({ k: 15 }, (arg) => { // 4.3.5: arg is {k: number}, 4.4.2: arg is 'any'
  console.log(arg.k);
});

f((a: number) => {});

playground link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.