When using square brackets like o['b']
, the o
object is treated as an any
type in Typescript, which means no type checks will be applied.
To receive warnings, you can set the noImplicitAny: true
attribute in your tsconfig.json
file. This will result in an error stating
Element implicitly has an 'any' type because type 'MyClass' has no index signature.
for
o['b']
. To work around this issue, you must explicitly declare that
o
should be treated as an any type like so:
(o as any)['b']
.
An exception to this rule is if you define an attribute in MyClass
that already exists. For example:
export class MyClass{
a: number;
"Weirdly-Named-Attribute": number;
}
const o = new MyClass();
o["a"] = 4; // compiles
o["Weirdly-Named-Attribute"] = 5; // compiles
o["b"] = 6; // Gives `Element implicitly has an 'any' type` error if `noImplicityAny` is enabled in tsconfig.