typescript - 为什么 Typescript 在索引到不可索引的类型时不会报错,有没有办法让它这样做?

标签 typescript indexing type-safety

在尝试使用 map 时类型,我曾多次尝试使用方括号获取和设置元素而搬起石头砸自己的脚。我意识到我需要使用 map.get(key)map.set(key,value) 但是在使用 Python 和 C# 字典这么久之后,我我很难通过我厚厚的头骨来理解这个。

let m = new Map<string, string>();

// This doesn't generate any error, though it 
//  doesn't do what someone might assume it
//  would (doesn't add an element to the map)
m["foo"] = "bar"

// This doesn't generate an error either
m[1] = 2; 

// This does generate an error, even though
//  in javascript, m.foo means the same as 
//  m["foo"], so why does typescript treat
//  them differently?
m.foo = "bar"

// This is what someone really should be
//  doing to add an element to the map
m.set("baz", "qux")

我使用 Typescript 的原因通常是因为它可以防止我做该类型不支持的愚蠢事情。但是,在这种情况下,Typescript 不会报错。它似乎并不关心我正在尝试使用方括号索引到 map 中。

事实上,即使对于像数字这样的原始数据类型,它似乎也不介意我做这样完全无意义的事情:

// Typescript allows you to index into any
//  type, even a number?!??!?!
let x = 3;
let y = 4;
x["crazy"] = "yes";

// But again the behaviour is inconsistent
// between indexing with [] versus .
// The following is an error in Typescript.
x.crazy = "no"

甚至是我自己的类(class)。

class MyClass {
    x: number;
}

let myInstance = new MyClass()
myInstance.x = 5;
myInstance["y"] = 10; // not an error

我的问题是:

  1. Typescript 允许对任何和所有类型进行索引的基本原理是什么?
  2. 考虑到 x.foo 与 javascript 中的 x["foo"] 同义,为什么 Typescript 对它们的处理方式如此不同?
  3. 有没有一种方法可以打开额外的检查来防止索引到不打算索引的类型?有没有一种方法可以将类型标记为不可索引,这样您就不会不小心尝试对其进行索引?

最佳答案

使用默认的编译器设置,您确实可以索引到您不应该索引到的对象。这样做可能是为了简化从 JS 到 TS 的迁移。

您可以使用 noImplicitAny 标志启用编译器关于索引的检查(any 的其他隐式使用),或者更一般地说,您可以使用 strict 标志启用额外检查.

关于typescript - 为什么 Typescript 在索引到不可索引的类型时不会报错,有没有办法让它这样做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48535201/

相关文章:

c++ - 模板类型定义 - 你的工作是什么?

node.js - 如何为默认导出类编写类型定义文件?

solr - 如何在 SOLR DIH HTTP API 中强制中止数据导入

python - 通过条件在 pandas csv 文件中创建新列

go - Go slice 索引符号背后的想法是什么?

java - Java 中嵌套集合/结构的类型安全展平

java - 从返回的接口(interface)进行转换?总是安全吗?

javascript - 了解 Angular 2 webpack 项目中的源代码符号链接(symbolic link)

javascript - TypeScript 错误 - 应有 1-2 个参数,但有 0 个或更多。 TS2556

angular - 使用 AWS Amplify & Cognito 调用 API 时安全 token 无效