gpt4 book ai didi

javascript - 流: Coercing an object-with-nullable-property to object-with-non-nullable-property?

转载 作者:行者123 更新时间:2023-11-29 23:49:58 28 4
gpt4 key购买 nike

有没有一种方法可以表达两种相关类型(一种具有可空属性,一种不具有),以便您可以在运行时进行检查后将一种强制转换为另一种?

例如 -

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

最佳答案

据我所知,Flow不支持这个。

使用类型转换需要您自担风险:

if (stat.count !== null) {
validStats.push(((stat: Object): StatWithCount))
}

关于javascript - 流: Coercing an object-with-nullable-property to object-with-non-nullable-property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997642/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com