The whole point of adding static types to JavaScript is to provide some guarantees about type safety. I noticed that array indexing seems to break type safety without using any dirty tricks like as any or the not null assertion operator.
let a: Array<number> = [1,2,3,4];
let b: number = a[4]; //undefined
This code does not cause any TypeScript errors, even though it is plain to see that it will violate type safety. It seems to me that the type of an Array<T> acted upon by the index operator [] should be type T | undefined, however the TypeScript compiler treats it as if it was type T.
Upon further investigation, I discovered that this behavior applies to use of the index operator on objects as well. It would seem that the index operator is not type safe in any case.
class Example {
property: string;
}
let c: Example = { property: "example string" }
let d: string = c["Not a property name"]; //undefined
Use of the index operator on an object with arbitrary key returns type any, which can be assigned to any type without causing type errors. However, this can be resolved by using the --noImplicitAny compiler option.
My question is why does something as basic as indexing on an array break type safety? Is this a design constraint, an oversight, or a deliberate part of TypeScript?