I’m struggling to understand why this example isn’t considered valid by the typescript compiler:
interface IExample<T> {
param: T
}
function testFunc<U, I extends IExample<U>>(myParam: U): I {
return { param: myParam };
}
The error produced is:
Type 'U' is not assignable to type 'I["param"]'.
My (assumedly incorrect) reading of this snippet is:
IExample<T>expectsparamto have typeT.Iis a subtype ofIExample<U>, meaningparamhas typeU.myParamhas typeUfrom the parameter annotation.- Therefore
myParamshould be a valid value forparamofI.
Prefixing the return value with <I> clears the error, so why does the error appear in the first place?
{ param: U }isn't assignable to generic typeI: I is an unknown type, which could have many more attributes and methods than just param. So{ param: myParam }is almost guaranteed to not be of type I.