Since the release of version 4.8.4, the TypeScript compiler has been flagging an issue with the following code:
type A = {v: number}
function get_the_first<T>(xs: T[]): T | undefined {
if (xs.length > 1)
return xs[0];
else
return undefined
}
function foo<T>(xs: T[], fielddb: keyof T) {
let a: T | undefined = get_the_first(xs);
if (a === undefined) {
} else {
console.log(a[fielddb]); // Error: Object is possibly 'null'
}
}
foo([{v: 42}], 'v')
I can't quite figure out why this warning message is appearing. The variable a
is either of type T
or undefined
, and it's already confirmed to not be undefined
.
Unless the issue lies in the fact that the compiler considers the generic type T
may include the null
type. If that's the case, what would be the best way to address this warning?