简体   繁体   English

如何基于参数字符串定义返回类型? Flowtype JavaScript

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

For example I got this fn: 例如,我得到这个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. 问题在于,退货始终是Bike或独立于此类型的Car 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 . 我想强制执行以下操作:当类型为a ,返回值始终为Car类型,而当类型bBike

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) . 注意: formatNotification的参数只能是一个对象,而不能是2个参数,例如formatNotification(type, data)

Still not a good solution but halfway working. 仍然不是一个很好的解决方案,但是已经成功了一半。

在此处输入图片说明

And the types: 以及类型:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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