【问题标题】:How to initialize typescript data-structure quickly inline如何内联快速初始化打字稿数据结构
【发布时间】:2020-05-05 14:55:22
【问题描述】:

我正在寻找一种快捷方式来创建一个快速的数据结构,我可以通过按键访问数据。
我想我可以为此使用自定义字典。

所以我有这个界面:

interface Dictionary<T> {
  [Key: string]: T;
}

我想初始化是这样的:

data: Dictionary<string> = {
    ['key']: { a: 1, b: 2 }
  } 

但是我遇到了错误Type '{}' is not assignable to type 'string'

有什么想法吗?

【问题讨论】:

  • 我不确定你想要实现什么,因为它不是有效的语法,1 和 2 都不是,{a: 1, b: 2} 不是字符串。 Dictionary 看起来像 {foo: 'hello', bar: 'world' }:一个带有与字符串值关联的键的对象。
  • 好的。但是你知道字符串、数字和对象不是一回事吗?在字符串字典中,您不能存储数字或对象。因为它们不是字符串。

标签: typescript interface


【解决方案1】:

{ a: 1, b: 2} 不是string,但您正试图将其用作具有索引签名[Key: string]: string 的对象中的属性值(因为Tstring)。

如果您希望值是具有属性ab 的对象,则需要为此使用适当的类型,而不是string。例如:

interface Dictionary<T> {
  [Key: string]: T;
}

const data: Dictionary<{ a: number, b: number }> = {
    key: { a: 1, b: 2}
};

或者更好的是,为它定义一个类型,并使用该类型:

interface Dictionary<T> {
  [Key: string]: T;
}

type Example = { a: number, b: number };
const data: Dictionary<Example> = {
    key: { a: 1, b: 2}
};

Live example on the playground


旁注 1:无需将计算属性语法与字符串文字 (['key']) 一起使用。只需使用字符串文字或属性名称文字即可。

旁注2:

我正在寻找一种快捷方式来创建一个快速的数据结构,我可以通过按键访问数据。

Map 对此有好处。或者,如果您事先知道键的值、定义的对象类型或Record&lt;K, T&gt;

【讨论】:

  • 记录实用程序对我来说效果很好。感谢您指出这一点!
猜你喜欢
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多