由于Javascript的性质,我一直在检查值是否!= null && != ''一直存在,因此我创建了一个函数来检查值是否为空,如下所示:
const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => {
return variable == null || (variable == '' && !allowEmptyString);
};
Run Code Online (Sandbox Code Playgroud)
问题是,其他方法不知道这意味着什么,因此我必须一直使用!以防止出现警告,例如:
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'
}
};
Run Code Online (Sandbox Code Playgroud)
我当前的解决方案是:
if (!isEmpty(val)) {
a = val!
}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以避免使用!来防止警告?
这是一个解决方案:
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);
}
Run Code Online (Sandbox Code Playgroud)
笔记:
===代替==;undefined价值观;allowEmptyString设置为true),将以undefined和处理空字符串null,并且编译器会错误地认为它不是字符串。Exclude为了模拟布尔值,参数的值被反转了(它可以工作,但是我不确定为什么)。exists功能但是我建议使用一个exists函数以避免双重反转。它更容易编写,也更易于使用:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |