Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inferring when using tuple as inputs [duplicate]

Tags:

typescript

This seems so obvious and simple, but I can't get it to work. Would love to get everybody's perspective to see if you can find what am I missing.

Playground

const objA: {foo:string} = { foo:'bar' };
const objB: {foo:string} = { foo: 'bar'};

fn([
  [objA, (val) => {}],
// ^^^^ type is corrent.
        // ^^^ expect type to be {foo:string} (same as position 1), but got `unknown`
  [objB, (val) => {}],
  // IBID
]);

declare function fn<
  Ax,
  Bx,
  A extends entry_T<Ax>,
  B extends entry_T<Bx>,
>(args: [A, B?]): void;

type entry_T<X> = [X, (val: X) => void];

like image 260
user1543574 Avatar asked Apr 01 '26 01:04

user1543574


1 Answers

Might be another case of type inference not working through multiple levels of generics. Pretty sure I have seen issues about that on Github, but they are hard to find again.

If it is not too much of a hassle, you could just drop the extra layer that wraps the tuple:

declare function fn<A, B>(args: [[A, Fun<A>], [B, Fun<B>]?]): void;
type Fun<X> = (val: X) => void;
like image 68
H.B. Avatar answered Apr 03 '26 17:04

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!