2

Consider the following:

function passAndInferType<S, T>(arg1: S, arg2: T) { return { arg1, arg2 }; }

const test = passAndInferType('hello', 'world'); 
//correctly infers type of test is {arg1: string, arg2: string}

const test2 = passAndInferType('hello', { foo: 'bar' }); 
//correctly infers type of test2 is {arg1: string, arg2: { foo: string }}

const test3 = passAndInferType<boolean, string>(false, { foo: 'bar' }); 
// correctly throws error on arg2 type

const test4 = passAndInferType<boolean>(false, { foo: 'bar' }); 
// error: expected 2 arguments but got 1
// desired: infers type of test4 {arg1: boolean, arg2: {foo: string}}}

What I'd like to achieve is defining a function where test4 type checks arg1 and correctly infers arg2: {foo: string}, but at present I get Error: Expected 2 arguments but got 1.

Any advice?

Michael.Lumley
  • 2,345
  • 2
  • 31
  • 53

0 Answers0