javascript – 为什么数组中的索引在TypeScript中打破了类型的安全性?


JavaScript添加静态类型的重点是提供有关类型安全性的一些保证.我注意到数组索引似乎打破了类型安全性而没有使用像任何或非null断言运算符那样的任何脏技巧.

let a: Array<number> = [1,2,3,4];
let b: number = a[4]; //undefined

此代码不会导致任何TypeScript错误,即使很明显它会违反类型安全性.在我看来,阵列的类型< T>由index []操作的应该是类型T |未定义,但TypeScript编译器将其视为类型T.

经过进一步调查,我发现这种行为也适用于在对象上使用索引运算符.在任何情况下,索引运算符似乎都不是类型安全的.

class Example {
  property: string;
}

let c: Example = { property: "example string" }
let d: string = c["Not a property name"]; //undefined

在具有任意键的对象上使用索引运算符返回类型any,可以将其分配给任何类型而不会导致类型错误.但是,这可以通过使用–noImplicitAny编译器选项来解决.

我的问题是为什么像数组上的索引那样基本的东西打破了类型安全?这是TypeScript的设计约束,疏忽还是故意的一部分?

最佳答案

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.

是.如果您关心严格的安全,请使用noImplicitAny.同样严格:true(strictNullChecks以及其他).

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?

有安全水平.严格是最强的.您可以选择对代码的严格程度.

更多

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

That said, traditionally programming languages have a hard boundary between what is and isn’t allowed by the type system. TypeScript is different in that it gives you control on where you put the slider.

点赞