I use flowType to write express router code, and let flow to check the req.body data, body data have multiple type, such as UserData(bbb type) or LoginData(ccc type). But when the body transform data to function, flow always says something wrong. Is there any good idea to support body have multiple type check? Here is a demo wrong code.
/* @flow */ declare type ccc = { ccc: string; } declare type bbb = { bbb: string; } declare type aaa = { body: bbb | ccc } function test(aaa: aaa) { const body = aaa.body test2(body) } function test2(body: ccc): string { return body['ccc'] }
Here's the error you get when running the supplied code with flow
:
34: test2(body)
^^^^^^^^^^^ function call
37: function test2(body: ccc): string {
^^^ property `ccc`. Property not found in
34: test2(body)
^^^^ object type
The main issue here is test2
. aaa
can have a body
value of either the bbb
or the ccc
type, which means that when you call
const body = aaa.body
test2(body)
body
can either be a match for type bbb
or for type ccc
, we don't know. Meanwhile, test2
explicitly only accepts an argument of type ccc
. Flow is seeing the possibility for bbb
type to be passed, which will of course, not have the ccc
property. At least one solution is to make the following change:
function test2(body: bbb | ccc): string {
if (typeof body.ccc === 'string') {
return body.ccc
}
return ''
}
We need bbb | ccc
bbb | ccc
because it can in fact be either option. Next, we need the typeof
check to ensure that we don't return undefined
in the case where we passed in a bbb
type. This removes the error.
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.