Why do tests 1 and 2 work here, but test 3 shows a compiler error at foo[barConst]++
: 'Object is possibly "undefined".'? I often need to access properties via bracket notation and thus like to have constants for these properties, but TypeScript doesn't allow this. It also doesn't work with const enum
s. Is it a bug or is there a good reason for the error?
const barConst = 'bar';
interface Foo {
[barConst]?: number;
}
function test1(foo?: Foo) {
if (foo && foo.bar) {
foo.bar++;
}
}
function test2(foo?: Foo) {
if (foo && foo['bar']) {
foo['bar']++;
}
}
function test3(foo?: Foo) {
if (foo && foo[barConst]) {
foo[barConst]++; // compiler error: 'Object is possibly "undefined".'
}
}
strictNullChecks
disabled. Why, though? P.S. disabling this setting is not an option for me. – Exchequer