Purpose
My goal is to establish an optional parameter unless a specific type is provided, in which case the parameter becomes mandatory.
Desired Outcome
I aim for the get
method below to default to having an optional parameter. However, if a type TT is passed when calling the get
method, it should then require a parameter of type TT.
export class Test<T = void> {
get<TT>(param: T & TT): Test<T & TT>
get<TT>(param: void | TT): Test<T & TT>
get<TT>(param: T & TT): Test<T & TT> {
return null as any;
}
}
const test = new Test();
test.get();
test
.get<{ name: string }>({ name: '' })
.get() // Expected 1 arguments, but got 0.
.get<{ age: number }>({ age: 23 }); // Property 'name' is missing in type '{ age: number; }' but required in type '{ name: string; }'
The above code will compile without errors, but my intention is for it to produce the specified error messages in the comments. Any suggestions on how I can achieve this?