【问题标题】:What does the type { [key: string]: boolean; } mean?什么类型 { [key: string]: boolean; } 意思是?
【发布时间】:2017-04-13 15:40:59
【问题描述】:

最近遇到这样的事情,一个函数声明:

static required(control: AbstractControl): {
  [key: string]: boolean;
};

这个返回值是什么?具有任意数量属性的对象,其中每个属性都是布尔值并具有名称,这似乎是一个字符串?我猜这更像是一个打字稿问题,但以防有人想知道我在哪里找到的 - 它是 Angular 的 Validators 类。

【问题讨论】:

标签: typescript


【解决方案1】:

这是一个键/值结构,在 typescript 中命名为 index signatures(或以前称为 indexable Types)。

键是string,值是boolean。例如:

let map : { [key: string]: boolean} = {};
map["foo"] = true;
map["bar"] = false;
map.foo = true;
map["foobar"] = "foo"; // Throws exception
map[1] = true; // Curiously doesn't throws exception

查看this sample on the Typescript Playground.

【讨论】:

  • 为什么map.foo = true; // Throws exception??
  • @lonewarrior556 代码“map.foo = true”实际上并没有引发异常。原始答案声称确实如此,但这是不正确的,因此答案是udated。但是,TypeScript Playground 链接仍然包含错误注释。
  • 遇到了类似的代码,其中一个逻辑分支返回 null,但返回类型是 {[key: string]: boolean} 它告诉我 null 不能分配给这种类型.也许我有严格的空类型检查而 hte 样本没有?我不知道如何使我的返回类型起作用。
猜你喜欢
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 2010-10-29
  • 2021-02-09
相关资源
最近更新 更多