One of the main purposes behind incorporating static types into JavaScript is to offer assurances regarding type safety. I have observed that utilizing array indexing appears to compromise type safety without resorting to any deceptive techniques like as any
or the not null assertion operator.
let a: Array<number> = [1,2,3,4];
let b: number = a[4]; //undefined
Despite the clear violation of type safety in the code example above, it does not trigger any TypeScript errors. It seems logical for the type of an Array<T>
operated upon by the index operator []
to be T | undefined
, but the TypeScript compiler treats it as simply T
.
Upon closer examination, I also noticed that this behavior extends to using the index operator on objects. It seems that the index operator lacks type safety across the board.
class Example {
property: string;
}
let c: Example = { property: "example string" }
let d: string = c["Not a property name"]; //undefined
Utilizing the index operator on an object with an arbitrary key results in a type of any
, which can then be assigned to any type without triggering type errors. However, this issue can be resolved by opting for the --noImplicitAny
compiler option.
My query is why does something as fundamental as array indexing end up compromising type safety? Is this intentional as part of TypeScript's design, an oversight, or a deliberate choice?