Flow:将具有nullable属性的对象强制转换为object-with-non-nullable-property?

时间:2017-03-24 10:54:16

标签: javascript flowtype

有没有办法表达两种相关类型 - 一种具有可空属性,一种没有 - 以这种方式在运行时检查后可以强制一种到另一种?

例如 -

type Stat = {
  count: ?number,
}
type StatWithCount = {
  count: number
}

let stats: Array<Stat> = [{count: null}, {count: 2}]
let validStats: Array<StatWithCount> = []

for (let i=0; i<stats.length; i++) {
  const stat = stats[i]
  if (stat.count !== null) {
    validStats.push(stat) // This type is incompatible with object type
  }
}

https://flowtype.org/try/#0C4TwDgpgBAysCGwoF4oG8BQUoGMD2ArgHbABcUA-EQQLYBGEATgDQYC+GoksCwA6gEtgACwDChEinRZcEslGr0m7DBgA2EJAGdeW8gEFGjeCAA8cRAD4pAbTT5i86mrVtm6ByXIAmNgF11TSgAN3g1AQATC2A9KENjM2jBEXFHa1QbAIwAMzxGKAAKDSQBZAAGAG4oAVMdRC0AOg0iAHMRKoEAak6ASmlsYqg6pFRhrRsBAOwBbMLhhs8kAEJkVGc1PsxsbFDwqN0GsAItYQLhnpkONiA

1 个答案:

答案 0 :(得分:1)

据我所知,flow不支持此功能。

使用类型转换风险自负:

window.location.hash = target;