[英]How can I define return value as truthy in Flowtype?
With a function like this the return value will always be truthy, not necessary true
, and not necessary any
. 有了这样的函数的返回值将始终是truthy,没必要
true
,并没有必要的any
。 Is there any way to define that the return value for this function will be truthy
? 有没有办法定义这个函数的返回值是
truthy
吗?
function cleanTruthy (value: any) {
if (!value) return true
return value
}
It seems this is possible by overloading a method in a separate module declaration. 看来这可以通过在单独的模块声明中重载方法来实现。 The following works (I'm not sure if it's possible without module declarations):
以下工作(我不确定是否可能没有模块声明):
/* @flow */
declare function cleanTruthy(V: false | 0 | null | typeof undefined | ""): true;
declare function cleanTruthy<V: any>(v: V): V;
const truthy: 1 = cleanTruthy(1);
const falsy: true = cleanTruthy(false);
Here is a working version . 这是一个工作版本 。
However, type polymorphism is not usually the best way to go, and flow will have to recompile every time you change a module file. 但是,类型多态通常不是最好的方法,每次更改模块文件时都必须重新编译流。
A better approach might be to create a function like this, that returns a solid boolean based on the logic of truthiness: 一个更好的方法可能是创建一个这样的函数,它返回一个基于真实性逻辑的实体布尔值:
function isTruthy(v: any): boolean {
return !!v;
}
if(isTruthy(v)) {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.