Basically, why does Typescript's inference not generate an error in the second example here:
type MyType<TRecord extends Record<string,any>> = {
rec: TRecord
rec2: TRecord
}
const myRec = { idFoo: 3 }
function createMyType<T extends MyType<Record<string,any>>>(obj: T):T {
return obj
}
const myType = createMyType({
rec: myRec,
rec2: 3, // <-- error here as expected
})
const myType2 = createMyType({
rec: myRec,
rec2: {}, // <-- no error here
})
In other words, why doesn't it realize that the generic parameter in createMyType doesn't actually satisfy the constraint because rec and rec2 aren't the same type? Or am I misunderstanding how the inference here is working (probably).
Clarification
Another way to ask this might be -- how can I type MyType or createMyType so that an error is noted in the second example because rec and rec2 are not the same type (TRecord)?
{}does fulfill the typeRecord<string, any>createMyTypethe genericTis constrained toMyTypeand and I don't understand how a given type ofMyTypecan be satisfied by a type whererecandrec2are not both the same type, i.e.TRecord