I'm having trouble finding an answer to this potentially duplicate question, so please redirect me if it has already been addressed.
My experience with generics in TypeScript has shown me that the inferred types can vary based on whether a generic is wrapped when used as an array member. Here are two examples:
// Setting up
type Wrapped<I> = { _i: I };
// Example where it doesn't work
function foo1<TInner extends unknown>(bar: Wrapped<TInner>[]) {
return bar;
}
const a = foo1([{ _i: 5 }, { _i: "six" }]); // TInner = number, compiler error for second array member despite inference
// Example where it works
function foo2<TInner extends Wrapped<unknown>>(bar: TInner[]) {
return bar;
}
const b = foo2([{ _i: 5 }, { _i: "six" }]); // TInner = Wrapped<number> | Wrapped<string>
Why does this happen? Is there missing information in the documentation? Can someone guide me to a clear explanation of how TypeScript infers generics?