[英]ImmutableJS/FlowType: Is it possible to typeCheck an array returned by a List.toJS()
Let's say I have this immutable list: 假设我有这个不变的清单:
type Friend = {
name: string,
phone: string
}
const aList: List<Friend> = List([...])
Now I have a function with the signature below, that should consume the friend's list: 现在,我有了一个带有以下签名的函数,该函数应该使用朋友的列表:
const doStuffs = (friends: Array<Friend>): any => {...}
I would like to call it with aList converted to array like this: 我想用aList转换成这样的数组来调用它:
doStuffs(aList.toJS())
But I have a flow error, aList.toJS()
is not an Array<Friend>
但是我有一个流错误,
aList.toJS()
不是Array<Friend>
Is it possible to typeCheck the result of aList.toJS()
or do I have to define my function like this: 是否可以类型检查
aList.toJS()
的结果,还是必须这样定义我的函数:
const doStuffs = (friends: Array<any>): any => {...}
If you're sure the .toJS()
method is returning an array of Friend
, use a typecast through any to let flow know. 如果您确定
.toJS()
方法返回的是Friend
数组,请使用any进行类型转换以使流程知道。
Eg 例如
const arrOfFriends = ((aList.toJS(): any): Array<Friend>)
I know it sometimes sucks to use any
, but it's useful if you're sure about what's coming out and you don't want to write your own variant of .toJS()
我知道有时使用
any
会很糟,但是如果您确定即将发生什么并且不想编写自己的.toJS()
变体, .toJS()
Alternatively, you could write a method that actually converts the List<Friend>
to an Array<Friend>
. 或者,您可以编写一个将
List<Friend>
实际转换为Array<Friend>
。 Maybe if you want to be really sure about the correctness of your code. 也许如果您想真正确定代码的正确性。 Personally, I would just go for the
any
typecast as above and write a couple of unit tests. 就个人而言,我只是去做上面的
any
类型转换,并编写几个单元测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.