For example I got this fn:
const aCar = {type: 'car', wheels: 4};
const aBike = {type: 'bike', wheels: 2};
const fn = (type:'a'|'b'):Car|Bike => {
if(type === `a`) return aCar;
if(type === `b`) return aBike;
}
The problem is that the return is always Bike
or a Car
indipendently of the type. I would like to enforce that when the type is a
the return is always of type Car
and when is b
the type to be Bike
.
Is this possible?
Something very close :
// @flow
const items = [1, 2, 3];
type FirstType = ((_: 'a') => number) & ((n: 'b') => Array<number>);
const first: FirstType = (n):any => {
if (n === "a") {
return items[0];
} else if(n === 'b') {
return items;
}
}
const a: number = first('a');
const b: Array<number> = first('b');
Thanks
I found a way to do what I need to with this code. Is overloading the function and then uses the argument as an object to define the return. Is quite OK solution but could be better.
Note: the argument of formatNotification
can only be an object and not 2 arguments like formatNotification(type, data)
.
Still not a good solution but halfway working.
And the types:
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.