網站搜尋

typescript - 有辦法同時檢查 `null` 和 `undefined` 嗎?


由於 TypeScript 是強型別的,單純使用 if() {} 來檢查 null 和 undefined 聽起來不太對。

TypeScript 有針對這個的專用函數或語法糖嗎?

答案#1

使用雜耍檢查,你可以一次測試 null 和 undefined:

if (x == null) {

如果你使用嚴格檢查,它只會對設置為 null 的值為真,對未定義的變量則不會評估為真:

if (x === null) {

你可以使用這個範例嘗試不同的數值:

var a: number;
var b: number = null;

function check(x, name) {
    if (x == null) {
        console.log(name + ' == null');
    }

    if (x === null) {
        console.log(name + ' === null');
    }

    if (typeof x === 'undefined') {
        console.log(name + ' is undefined');
    }
}

check(a, 'a');
check(b, 'b');

輸出

「a == null」

「a 未定義」

"b == null"

"b === null"

答案#2

if( value ) {
}

如果 value 不是以下情況,將會評估為 true:

  • null
  • undefined
  • NaN
  • 空字串 ''
  • 0
  • false

TypeScript 包含 JavaScript 的規則。

答案#3

在 TypeScript 3.7 中,我們現在有 可選鏈接 和 空值合併 來同時檢查 null 和 undefined,例如:

let x = foo?.bar.baz();

這段程式碼將檢查 foo 是否已定義,否則它將返回 undefined

舊方式 :

if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} 

這個:

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

使用可選鏈將會是:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

另一個新功能是 空值合併,例如:

let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar

舊方法:

let x = (foo !== null && foo !== undefined) ?
foo :
bar();

獎金

答案#4

TypeScript 是否有專門的函數或語法糖來實現這個

TypeScript 完全理解 JavaScript 版本,即 something == null。

TypeScript 將會透過這些檢查正確排除 null 和 undefined。

更多

https://basarat.gitbook.io/typescript/recap/null-undefined

答案#5

簡單回答

雖然 Typescript 是一種強類型語言,但它也繼承了 Javascript 在指標和變數初始化上的相同問題。
Javascript 不會檢查變數是否存在於當前上下文中,因此常見的 undefined 狀態。

評估值是否不是null、undefined、0、false、""或NaN:

if ( value )
or
if ( !!value )

對於負條件,檢查該值是否為 null、undefined、0、false、"" 或 NaN:

if ( !value )

測試是否為 null 或 undefined:

if ( value == null )

僅測試 null:

if ( value === null )

僅測試 undefined:

if ( value === undefined )

更詳細的回答

1- 如果值 不是以下情況:null、undefined、NaN、空字串 ''、0、false,則會評估為 true
如果值是 null、undefined、NaN、空字串、0 或 false,則會執行 else 條件。

if ( value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}
if ( !!value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}

2- 如果你想要一個否定條件,那麼你將需要使用:

if ( !value ) {
  console.log('value is 0, "", false, NaN, null or undefined');
} else {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
}

3- 它將評估值是否為 null 或 undefined

if ( value == null ) {
  console.log('is null or undefined');
} else {
  console.log('it isnt null neither undefined');
}

4- 使用布林值進行測試是行不通的。
如果值是 null、undefined、0、空字串、NaN,它既 不會 評估為 true,也不會評估為 false。
兩個條件都會始終進入 else 條件。
除非值是一個布林變數。

if ( value==true ) {
} else { 
}
if ( value==false ) {
} else { 
}

答案#6

我在 TypeScript Playground 上做了不同的測試:

http://www.typescriptlang.org/play/

let a;
let b = null;
let c = "";
var output = "";

if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";

console.log(output);

給出:

a is null or undefined
b is null or undefined
c is defined

所以:

  • 檢查 (a == null) 是否正確以判斷 a 是否為 null 或 undefined
  • 檢查 (a != null) 是否正確以判斷 a 是否已定義
  • 檢查 (a) 是否錯誤以確認 a 是否被定義

答案#7

你可能想要嘗試

if(!!someValue)

使用 !!。

解釋

第一個 ! 將把你的表達式轉換成 boolean 值。

那麼 !someValue 當 someValue 是 假值 時為 true,當 someValue 是 真值 時為 false。這可能會令人困惑。

透過再加入另一個 !,當 someValue 為 truthy 時,這個表達式現在為 true,而當 someValue 為 falsy 時,則為 false,這樣管理起來會容易得多。

討論

那麼,為什麼我要費心去使用 if (!!someValue),而像 if (someValue) 這樣的做法就能給我相同的結果呢?

因為 !!someValue 恰好是一個布林表達式,而 someValue 則可以是任何東西。這種表達式現在將允許編寫函數(而天啊,我們真需要那些函數),比如:

isSomeValueDefined(): boolean {
  return !!someValue
}

而不是:

isSomeValueDefined(): boolean {
  if(someValue) {
    return true
  }
  return false
}

我希望這有幫助。

答案#8

對於 Typescript 2.x.x,你應該以以下方式進行(使用類型保護):

簡而言之

function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}

為什麼?

這樣 isDefined() 就會尊重變數的類型,接下來的程式碼也會考慮到這個檢查。

範例 1 - 基本檢查:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}

範例 2 - 類型尊重:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}

答案#9

我認為這個答案需要更新,請查看舊答案的編輯歷史。

基本上,你有三種不同的情況:null、undefined 和 undeclared,見下面的程式片段。

// bad-file.ts
console.log(message)

你會收到一個錯誤,說變量 message 未定義(也就是未聲明),當然,Typescript 編譯器不應該允許你這麼做,但真的沒有任何東西可以阻止你。

// evil-file.ts
// @ts-gnore
console.log(message)

編譯器會很高興地只編譯上面的程式碼。所以,如果你確定所有變數都已宣告,你就可以直接這麼做

if ( message != null ) {
    // do something with the message
}

上面的程式碼會檢查 null 和 undefined,但如果 message 變數可能未宣告(為了安全起見),你可以考慮以下程式碼

if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}

注意:這裡的順序 typeof(message) !== 'undefined' && message !== null 非常重要,你必須先檢查 undefined 狀態,否則這將與 message != null 相同,感謝 @Jaider。

答案#10

if(data){}

它是 mean !data

  • 空值
  • 未定義
  • 假
  • ....

答案#11

更新(2020年9月4日)

你現在可以使用 ?? 運算子來驗證 null 和 undefined “值”,並設定預設值。例如:

const foo = null;
const bar = foo ?? 'exampleValue';
console.log(bar); // This will print 'exampleValue' due to the value condition of the foo constant, in this case, a null value

作為一種冗長的方式,如果你只想比較 null 和 undefined 值,請參考以下範例程式碼:

const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion

if (somethingToCompare == (undefined || null)) {
  console.log(`Incoming value is: ${somethingToCompare}`);
}

如果 incomingValue 未被宣告,TypeScript 應該會回傳例外。如果它已被宣告但未被定義,console.log() 會回傳「Incoming value is: undefined」。請注意,我們並未使用嚴格相等運算子。

「正確」的方法(詳細請查看其他答案),如果 incomingValue 不是 boolean 類型,只需判斷它的值是否為 true,這將根據常數/變數的類型來評估。一個 true 字串必須使用 = '' 顯式定義為字串。否則,它將被評估為 false。讓我們在相同的情境下檢查這個情況:

const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;

if (somethingToCompare0) {
  console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}

// Now, we will evaluate the second constant
if (somethingToCompare1) {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}