嵌套对象类型定义

时间:2020-01-03 01:37:40

标签: typescript

我有一个嵌套对象,我想为它写一个类型定义。这是对象:

const colors = {
  grayscale: {
    black: '#141414',
    darkGray: '#303030',
    white: '#F0F0F0',
  },
  green1: '#1DB954',
  green2: '#1ED760',
}

这是我尝试编写类型定义的方式:

interface ObjectOf<V> {
  [_: string]: V
}

type ColorObject = ObjectOf<string> | string
type Colors = ObjectOf<ColorObject>

const colors: Colors = {
  ... (same object as above)
}

我使用ObjectOf<V>来创建一个对象,该对象可以具有任何字符串形式的键,但是只能包含类型V的值。这似乎适用于未嵌套的对象。

当我尝试像这样使用该对象:colors.grayscale.black时,打字稿编译器给了我这个错误:

Property 'black' does not exist on type 'ColorObject'.
  Property 'black' does not exist on type 'string'.  TS2339

  > 82 |     backgroundColor: colors.grayscale.black,
       |                                       ^

看来打字稿正在忽略ColorObject可以是ObjectOf<>的事实,这意味着任何字符串都应该是有效的键。相反,它认为它只能是字符串,因此获取black对象的grayscale键失败。为什么会这样,和/或如何修复类型定义,以便可以按原样使用我的colors对象?

1 个答案:

答案 0 :(得分:1)

以下内容如何:

ref.on('child_removed', function(oldChildSnapshot) {
  var oldChildData = oldChildSnapshot.val();

  L.removeMarker(...)   //Just inventing a method name here!
});

我倾向于在有一些具体结构的地方使用它,并且我想以此为基础建立牢固的合同。我只能导出类型,并且该应用程序的真实来源将是colors对象。当您添加删除其中的内容时,类型会自动更新。缺点很少,但我相信仍然有用。