Why does indexing in an array interrupt security type in TypeScript?

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]; //undefined

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"]; //undefined

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?

+4
source share
1 answer

any, . , -noImplicitAny .

. noImplicitAny, . strict:true ( strictNullChecks, ).

, - , ? , TypeScript?

. strict . , .

https://basarat.gitbooks.io/typescript/content/docs/options/intro.html

, , . TypeScript , , .

+1

Source: https://habr.com/ru/post/1683273/


All Articles