this[variable]
and this[stringLiteral]
have different behavior #29042
Closed
Description
opened on Dec 15, 2018
TypeScript Version: 3.3.0-dev.201xxxxx, --strictNullChecks, no other strict flags
Search Terms:
string literal types property access
Code
class X {
x: number | undefined;
constructor() {
this.x = 5;
// Type checks, this.x is `number`
this.x.toString();
// Type checks, this['x'] is `number`
this['x'].toString();
// Types `this[thing]` as `number | undefined`
// and throws an error as "Object is possibly undefined"
const thing: 'x' = 'x';
this[thing].toString();
}
}
Expected behavior:
this['x']
and const thing: 'x' = 'x'; this[thing]
should resolve to the same thing.
Actual behavior:
const thing: 'x' = 'x'; this[thing]
resolves to the base property type (number | undefined
) without having the context that it's been assigned in the same block
Disclaimer: if you also use --strictPropertyInitialization Typescript does the correct thing and permits all three.
Related Issues:
Activity