class Base {}
function log(arg: number) {
console.log(arg);
}
function fn<T extends typeof Base>(
instance: Partial<InstanceType<T>>,
key: keyof InstanceType<T>,
) {
const val = instance[key];
if (val) {
log(val);
}
}
I get:
Argument of type 'InstanceType<T>[keyof InstanceType<T>] | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.
Shouldn't if (val) guard against undefined? It works if I change it to log(val ?? 0).
Also, I'm surprised log(val ?? 0) works. val could be a truthy value that's not a number, but log() expects a number. Why doesn't this throw an error?