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