I'm working with code that looks like this:
type Boxed<T> = { inner: T }
const box = <T>(inner: T): Boxed<T> => ({ inner });
function test<T extends Boxed<any>>(...args: T[]): T extends Boxed<infer I> ? I : never {
return args[0].inner;
}
In this scenario, the Boxed<T>
represents a complex generic type, and the function is designed to "unbox" the inputs to derive a value of the union type based on all input values. However, when we pass in specific values, the type T
defaults to the type of the first argument, causing any additional arguments to be rejected:
test(box(0), box('str'));
// Argument of type 'Boxed<string>' is not assignable to parameter of type 'Boxed<number>'.
Interestingly, if we destructure a tuple when passing the arguments, it works as expected:
test(...[box(0), box('str')]);
// Successfully results in type (string | number).
Is there a way to modify the function definition so that the more user-friendly first example would also work?