[英]How can I fix the following javascript code to make it work with flowtype?
Given the following snippet I am getting the error below... how should I can fix it? 鉴于以下代码段,我收到以下错误...我该如何解决?
This type is incompatible with the expected return type of number enum.
此类型与数字枚举的预期返回类型不兼容。
type Size = 1 | 2 | 3;
const GetSize = (): Size => {
const result: number = parseInt(Math.random() * 20);
if (result > 3) {
return 3;
}
return result;
};
You can try it online ... 你可以在线试试 ......
Edit: 编辑:
The issue is related to the conversion from integer to enum. 该问题与从整数到枚举的转换有关。
Math.random() returns a "floating point" number between [0, 1). Math.random()返回[0,1]之间的“浮点”数。 So it can return 0.5 or 0.31231.
所以它可以返回0.5或0.31231。 The types are indeed incompatible.
这些类型确实不兼容。 Even if it returned either 0 or 1 with equal probability, you'd still be outside the constraints of your Size type.
即使它以相同的概率返回0或1,您仍然不在Size类型的约束之内。
One way to fix this would be to do something like return (int)result + 1
. 修复此问题的一种方法是执行类似
return (int)result + 1
。 But I don't know if Flow is smart enough to understand that. 但我不知道Flow是否足够聪明才能理解。 A proper way would be to have
if/else
s for all cases you anticipate, and explicitly return 1, 2 or 3 based on those. 一种正确的方法是为你预期的所有情况设置
if/else
,并根据这些情况明确返回1,2或3。 Like you're doing for results larger than 3. 就像你在为大于3的结果做的那样。
Math.random()
returns a random number between 0 and 1, it's return type is number
. Math.random()
返回0到1之间的随机数,它的返回类型是number
。
Your defined return type is stricter than that, it's 1 | 2 | 3
你定义的返回类型比那更严格,它是
1 | 2 | 3
1 | 2 | 3
1 | 2 | 3
. 1 | 2 | 3
。 Math.random()
doesn't comply with with the return type you defined, so it can't be returned. Math.random()
不符合您定义的返回类型,因此无法返回。 That's the error. 那是错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.