【问题标题】:Flow: declare type for nested objects流程:声明嵌套对象的类型
【发布时间】:2018-04-23 17:24:38
【问题描述】:

我有一个非常简单的问题,关于给对象一个带有流的类型,这里是一个代码示例:

type Test = {
  a: string
}

const t = {
  test_object1: {
    a: 'foo'
  },
  test_object2: {
    a: 'bar'
  }
};

如果 Test_object 是对象中的 self,我如何将它们添加到我的 test_object 中?

我试过了:

const t = {
  test_object1: {
    a: 'foo'
  } : Test,
  test_object2: {
    a: 'bar'
  } : Test
};

const t = {
  test_object1<Test>: {
    a: 'foo'
  },
  test_object2<Test>: {
    a: 'bar'
  }
};

但没有一个有效。

【问题讨论】:

  • 要设置内联注释,您需要在值周围加上括号:({a: 'foo'} :Test)

标签: javascript flowtype


【解决方案1】:

我认为这可行:

type Test = {
  a: string
}

const t: {
  test_object1: Test,
  test_object2: Test,
} = {
  test_object1: {
    a: 'foo'
  },
  test_object2: {
    a: 'bar'
  }
};

```

来源:https://flow.org/en/docs/types/objects/#toc-object-type-syntax

【讨论】:

    【解决方案2】:

    您必须键入整个对象,我认为您不能进行“嵌套”键入:

    const t = { ... } : { test_object1: Test }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      相关资源
      最近更新 更多