TypeScript Version: 3.7.0-dev.20190824
Search Terms:
Object is possibly undefined
TS2532
Code
interface IData {
data: number;
}
interface IMyObject {
[index: string]: IData | undefined;
}
const myObject: IMyObject = {};
const objectKey = 'something';
myObject[objectKey] = {
data: 5
}
console.log(myObject[objectKey].data); // TS2532: Object is possibly 'undefined'
Expected behavior:
Code compiles without error.
Actual behavior:
Error: TS2532: Object is possibly 'undefined'. on myObject[objectKey]
Playground Link:
http://www.typescriptlang.org/play/index.html#code/JYOwLgpgTgZghgYwgAgJIBE5jsg3gKGWQBMs4AuZEAVwFsAjaAbnwF999RJZEVUBZAJ4B5egCsICMHkLIA2qGIQAHpQDOYKKADmAXUoYyyAD7JqIJTFARiLdvgQB7EBuS0R4yWANDREqcgAvHisLE4u0o6eUgDSEIJByADkao60EGAAFjpJLPjufl5yUf5gcYK6iQREpNiUAKxsHOGpADYQAHStjtoAFAXRYMWD5bodtXAAlExAA
Related Issues:
#13778, #17960, #26599, #29642
It seems related issues have been around for a long time, in addition issue #26599 was closed as a "wontfix". This is weird to me because it seems Typescript should be able to detect that objectKey has not changed between the object assignment and query.
TypeScript Version: 3.7.0-dev.20190824
Search Terms:
Object is possibly undefined
TS2532
Code
Expected behavior:
Code compiles without error.
Actual behavior:
Error:
TS2532: Object is possibly 'undefined'.onmyObject[objectKey]Playground Link:
http://www.typescriptlang.org/play/index.html#code/JYOwLgpgTgZghgYwgAgJIBE5jsg3gKGWQBMs4AuZEAVwFsAjaAbnwF999RJZEVUBZAJ4B5egCsICMHkLIA2qGIQAHpQDOYKKADmAXUoYyyAD7JqIJTFARiLdvgQB7EBuS0R4yWANDREqcgAvHisLE4u0o6eUgDSEIJByADkao60EGAAFjpJLPjufl5yUf5gcYK6iQREpNiUAKxsHOGpADYQAHStjtoAFAXRYMWD5bodtXAAlExAA
Related Issues:
#13778, #17960, #26599, #29642
It seems related issues have been around for a long time, in addition issue #26599 was closed as a "wontfix". This is weird to me because it seems Typescript should be able to detect that
objectKeyhas not changed between the object assignment and query.