[英]TypeScript with strictNullChecks and function to detect null values
Due to the nature of Javascript, I get myself checking if a value is != null && != ''
all the time, so I created a function to check if values are empty, like this: 由于Javascript的性质,我自己检查值是否为!= null && != ''
所以我创建了一个函数来检查值是否为空,如下所示:
const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => {
return variable == null || (variable == '' && !allowEmptyString);
};
The problem is, other methods don't have a knowledge of what this means, so I have to use !
问题是,其他方法不知道这意味着什么,所以我必须使用!
all the time to prevent warnings, for example: 所有时间都要防止警告,例如:
const foo = (val?: number): void => {
let a = 0;
if (!isEmpty(val)) {
a = val;
// let a: number;
// Type 'number | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'
}
};
My current solution is to do: 我目前的解决方案是:
if (!isEmpty(val)) {
a = val!
}
Is there a way to avoid using !
有没有办法避免使用!
to prevent warnings? 防止警告?
Here is a solution: 这是一个解决方案:
function isEmpty(variable: string | null | undefined, allowEmptyString?: boolean): variable is Exclude<undefined | null, string>
function isEmpty<T>(variable: T | null | undefined): variable is Exclude<undefined | null, T>
function isEmpty(variable: any, allowEmptyString = false): boolean {
return variable === null
|| variable === undefined
|| (variable === '' && !allowEmptyString);
}
Notes: 笔记:
===
instead of ==
; 使用===
而不是==
; undefined
values; 照顾undefined
值; allowEmptyString
set to true
) an empty string is processed as undefined
and null
, and the compiler will mistakenly believe it is not a string. 默认情况下(没有将参数allowEmptyString
设置为true
),空字符串将被处理为undefined
和null
,编译器将错误地认为它不是字符串。 Exclude
are reversed in order to simulate a "not" on the boolean value (it works but I'm unsure why). Exclude
参数是相反的,以便模拟布尔值上的“not”(它有效,但我不确定为什么)。 exists
function ......或exists
功能 But I suggest an exists
function in order to avoid the double inversion. 但我建议使用exists
函数以避免双重反转。 It is easier to write, and easier to use: 它更容易编写,更易于使用:
function exists(variable: string | null | undefined, allowEmptyString?: boolean): variable is string
function exists<T>(variable: T): variable is NonNullable<T>
function exists(variable: any, allowEmptyString = false): boolean {
return variable !== null
&& variable !== undefined
&& (variable !== '' || allowEmptyString);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.