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]
Related Issues:
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.
If anyone else is looking for a workaround,
interface IData {
data: number;
}
interface IMyObject {
[index: string]: IData | undefined;
}
const myObject: IMyObject = {};
const objectKey = 'something';
myObject.something = {
data: 5
}
console.log(myObject.something.data);
Just don't use string literals/constants. Use dot notation instead.
Just don't use string literals/constants. Use dot notation instead.
Good solution, but doesn't work when objectKey is a variable :)
What I posted is just a demonstration of the issue, in most cases the object keys are not constant but variables or parameters passed to a function.
If the key is truly variable, then this is related to #31445: TS isn't equipped to understand that two mentions of obj[key] access the same property in both places; since it doesn't even know that, it doesn't make sense to perform any narrowing on it.
Yep, duplicate of #31445 (and some others).
Most helpful comment
If the key is truly variable, then this is related to #31445: TS isn't equipped to understand that two mentions of
obj[key]access the same property in both places; since it doesn't even know that, it doesn't make sense to perform any narrowing on it.