简体   繁体   中英

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:

doStuffs(aList.toJS())

But I have a flow error, aList.toJS() is not an Array<Friend>

Is it possible to typeCheck the result of aList.toJS() or do I have to define my function like this:

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.

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()

Alternatively, you could write a method that actually converts the List<Friend> to an 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM