简体   繁体   中英

How to define a type of return based on an argument string? Flowtype javascript

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.

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