The whole point of adding static types to JavaScript is to provide some type safety guarantees. I noticed that indexing the array seems to violate type safety without using any dirty tricks, such as as anyeither the null null operator.
let a: Array<number> = [1,2,3,4];
let b: number = a[4];
This code does not cause any TypeScript errors, although it is clear that it will violate type safety. It seems to me that the type Array<T>that the index operator acts on []must be a type T | undefined, however, the TypeScript compiler treats it as if it were a type T.
In further research, I found that this behavior also applies to the use of the index operator on objects. It would seem that the index operator is not safe anyway.
class Example {
property: string;
}
let c: Example = { property: "example string" }
let d: string = c["Not a property name"];
Using an index operator for an object with an arbitrary key returns a type anythat can be assigned to any type without causing type errors. However, this can be solved using the --noImplicitAnycompiler option .
My question is, why is something as basic as indexing at the level of protection against array breaking? Is this a constructive restriction, supervision, or an intentional part of TypeScript?
source
share