gpt4 book ai didi

javascript - ImmutableJS/FlowType : Is it possible to typeCheck an array returned by a List. toJS()

转载 作者:行者123 更新时间:2023-12-03 02:03:28 24 4
gpt4 key购买 nike

假设我有这个不可变列表:

type Friend = {
name: string,
phone: string
}

const aList: List<Friend> = List([...])

现在我有一个具有以下签名的函数,它应该使用 friend 的列表:

const doStuffs = (friends: Array<Friend>): any => {...}

我想将 aList 转换为数组来调用它,如下所示:

doStuffs(aList.toJS())

但是我有一个流程错误,aList.toJS()不是Array<Friend>

是否可以输入检查aList.toJS()的结果或者我是否必须像这样定义我的函数:

const doStuffs = (friends: Array<any>): any => {...}

最佳答案

如果您确定.toJS()方法返回 Friend 的数组,使用typecast through any让流程知道。

例如

const arrOfFriends = ((aList.toJS(): any): Array<Friend>)

我知道有时使用 any 很糟糕,但是如果您确定将会出现什么情况并且您不想编写自己的 .toJS() 变体,那么它会很有用。

或者,您可以编写一个实际转换 List<Friend> 的方法。到Array<Friend> 。也许如果您想真正确定代码的正确性。就我个人而言,我只会选择 any如上所述进行类型转换并编写几个单元测试。

关于javascript - ImmutableJS/FlowType : Is it possible to typeCheck an array returned by a List. toJS(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917230/

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