TypeScript-去除null和undefined检测


先不管三七二十一,首先来看一个函数的定义,该函数的内部返回了一个函数的回调,主要作用就是获取一个字符串的长度,可是呢函数的入参是一个联合类型,如下:

function getLength(value: (string | null | undefined)) {
    value = 'abc';
    return () => {
        return value.length;
    }
}

报错的原因就是说,该函数的入参呢,有可能是 null 和 undefined 如果是 null 和 undefined 就没有 .length 这个属性所以编译器就会报错,那么这个问题呢,在之前是利用 || 进行解决的解决代码如下:

function getLength(value: (string | null | undefined)) {
    value = 'abc';
    return () => {
        return (value || '').length;
    }
}

let fn = getLength('BNTang');
let res = fn();
console.log(res);

除了如上的方式进行解决以外,还有一种百试不爽的方式就是使用类型断言:

function getLength(value: (string | null | undefined)) {
    value = 'abc';
    return () => {
        return (value as string).length;
    }
}

let fn = getLength('BNTang');
let res = fn();
console.log(res);

如上除了使用类型断言以外,还可以使用类型断言的简写方式来进行简化代码, 类型断言的简写方式就是在变量的后面加一个感叹号 !! 的含义就是告诉编译器,这个变量一定不是 nullundefined

function getLength(value: (string | null | undefined)) {
    value = 'abc';
    return () => {
        return value!.length;
    }
}

let fn = getLength('BNTang');
let res = fn();
console.log(res);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM