简体   繁体   English

如何在Flowtype中将返回值定义为truthy?

[英]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.

相关问题 如何检查这个 function 是否为真,或者如果为假则返回一个空数组? - How can I check this function for truthy or return an empty array if falsy? 我如何检查空字符串是否被视为真实值 - How can i make check for empty string to be considered as truthy value 如何基于参数字符串定义返回类型? Flowtype JavaScript - How to define a type of return based on an argument string? Flowtype javascript 使用结构化 json 来确定真实逻辑,我如何最终使用 javascript 返回一个布尔值? - Using structured json to determine truthy logic, how can I ultimately return a boolean with using javascript? flowtype:如何通过参数计数/类型重载函数返回类型? - flowtype: how can i overload function return types by argument count/types? 如何有条件地返回具有许多真实变量排列和组合的结果? - How can I conditionally return a result with many permutation and combination of truthy variables? 如何解决FlowType中的“无法访问可能为空值的属性”? - How can I resolve “Property cannot be accessed on possibly null value” in FlowType? 如何获得数组的真实结果总数? - How can I get the total number of truthy results of my array? 如何修复以下javascript代码以使其与flowtype一起使用? - How can I fix the following javascript code to make it work with flowtype? Polyfill for object.value返回真实断言 - Polyfill for object.value to return truthy assertion
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM