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);
}
}
Check out the code in the TS Playground: here
The issue arises when trying to assign 'undefined' to a parameter that expects a 'number.' This can be solved by using the nullish coalescing operator like so: log(val ?? 0)
.
It may seem surprising that log(val ?? 0)
works, as val
could potentially be a truthy value that is not a number. However, TypeScript does not throw an error in this scenario.