Issue
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 enums. 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".'
}
}
Solution
Narrowing the property access via computed propertyNames/literal expressions seems to be not possible currently. Have a look at this issue and its PR, also that issue.
You can narrow property access in bracket notation with string literals like for example foo["bar"]. Dynamic expressions like foo[barConst] don't work. Assigning foo[barConst] to a variable and working/narrowing down this variable instead is an alternative, but costs an additional declaration.
In your case the simplest solution would be to just cast the expression with non-null assertion operator !. As you do a pre-check for a falsy value, you are safe here:
function test3(foo?: Foo) {
if (foo && foo[barConst]) {
foo[barConst]!++;
}
}
Answered By - ford04
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.