【问题标题】:How can I type a default export using Flow?如何使用 Flow 键入默认导出?
【发布时间】:2023-04-04 16:28:02
【问题描述】:

如何使用 Flow 键入默认导出? Flow 有办法做到这一点吗?

期望的结果:

// index.js
type complexThing = {
  a: string
}
type Thing = {
  x: number,
  y: boolean,
  z: complexThing
}

export default {
 x: 0,
 y: true,
 z: {a: 'hello'}
} : Thing // this says my default export is a Thing

可接受的替代方案:

或者,我不介意内联输入每个对象属性,但我认为这在语法上是不可能的:

export default {
 // I don't know how to add type signatures here
 x: 0, // number
 y: true, // boolean
 z: {a: 'hello'} // complexThing
}

不是我想要的:

想要做的是存储一个变量,只是为了流式输入它:

// index.js
type complexThing = {
  a: string
}
type Thing = {
  x: number,
  y: boolean,
  z: complexThing
}

const myThing: Thing = {
 x: 0,
 y: true,
 z: {a: 'hello'}
}

export default myThing

【问题讨论】:

    标签: javascript ecmascript-6 flowtype


    【解决方案1】:

    您正在执行typecast,因此您需要在对象周围使用括号,例如改变

    export default {
      x: 0,
      y: true,
      z: {a: 'hello'}
    } : Thing
    

    export default ({
      x: 0,
      y: true,
      z: {a: 'hello'}
    } : Thing)
    

    【讨论】:

    • 啊哈,是的,我现在明白了。 export default {} 是一个表达式,所以它需要一个类型转换来捕获类型签名。同样的事情也适用于通过对象文字内联输入对象属性:export default { x: (0: number) } 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2022-07-10
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    相关资源
    最近更新 更多