繁体   English   中英

引用带点符号的键,类型为{[x:字符串]:字符串}

[英]Refer to a key with dot notation, type is { [x: string]: string}

如何在键可以是任何字符串的情况下引用对象的属性?

我希望编译器不会在最后一行上抛出错误:

export type apple = { [x: string]: string }

export type pie = {
  fruit: apple;
}

let myPie: pie = {
  fruit: {
    appleVariety: 'Granny Smith'
  }
}

console.log(myPie.fruit.appleVariety);

您可能拥有一个正在使用的可索引对象,例如:

type apple = { [x: string]: string };
let a: apple = { appleVariety: 'Granny Smith' }
let variety = a['appleVariety'];
let something = a['something']; // no error even though it's undefined

或在对象中指定属性:

type apple = { appleVariety: string };
let a: apple = { appleVariety: 'Granny Smith' }
let variety = a.appleVariety;
let something = a.something; // Error: Property 'something' does not exist on type '{ appleVariety: string; }'.

您不能将两者混在一起。
其背后的原理是,如果您知道属性名称,则在接口/类型定义中明确包含它们。
但是,如果您在一个对象中只有一组属性,那么编译器将不会检查所使用的属性名称,而只会检查类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM