在Flow中定义由其他对象类型组成的对象

时间:2016-12-14 15:29:20

标签: flowtype

我有一个看起来像这样的对象:

const myObject = {
  a: {
    id: 'abc'
  },
  b: {
    id: 'def'
  },
  c: {
    id: 'ghi'
  },
}

a,b和c都具有相同的结构,所以我想为那些(下面的abcType)定义一个类型,并确保myObject包含这些类型。

基本上是这样的:

type abcType = {
  id: String
}

type myObjectType = {
  [whateverKey]: abcType
  // ^^ Dummy code, this doesn’t actually work
}

但是我似乎找不到在Flow中定义它的正确方法。是谁遇到了同样的问题?

1 个答案:

答案 0 :(得分:1)

type abcType = {
  id: string // lower-case 's'
}

type myObjectType = {
  [string]: abcType // 'string' type for the object keys.
};

const myObject: myObjectType = {
  a: {
    id: 'abc'
  },
  b: {
    id: 'def'
  },
  c: {
    id: 'ghi'
  },
}

应该就是您所需要的一切。

相关问题