TypeScript初心者でも安心!nullとundefinedのチェックをマスターしよう
TypeScriptでnullとundefinedを同時にチェックする方法
== nullを使用する
これは最も簡単な方法で、==
演算子を使用して変数をnull
と比較します。
let foo: string | null = "bar";
if (foo == null) {
// fooはnullまたはundefined
}
この方法は、null
とundefined
の両方をチェックするのに便利ですが、厳密な比較ではないことに注意が必要です。
=== nullと=== undefinedを使用する
===
演算子を使用して、変数をnull
またはundefined
と厳密に比較することができます。
let foo: string | null = "bar";
if (foo === null) {
// fooはnull
} else if (foo === undefined) {
// fooはundefined
}
この方法は、null
とundefined
を区別する必要がある場合に便利です。
オプションプロパティとnull合体演算子を使用する
TypeScript 2.0以降では、オプションプロパティとnull合体演算子を使用して、nullまたはundefinedの値を安全にアクセスすることができます。
interface Person {
name: string;
}
let person: Person | null = {
name: "John Doe",
};
const name = person?.name; // personがnullまたはundefinedの場合、nameはundefinedになる
if (name) {
// nameはnullまたはundefinedではない
}
この方法は、コードをより簡潔に記述できるという利点があります。
in
演算子を使用して、オブジェクトのプロパティがnull
またはundefined
かどうかを確認することができます。
let person: Person | null = {
name: "John Doe",
};
if ("name" in person) {
// personはnameプロパティを持っている
}
この方法は、オブジェクトのプロパティの存在を確認するのに便利です。
型ガードを使用する
TypeScript 3.7以降では、型ガードを使用して、変数の型を絞り込むことができます。
function isPerson(obj: any): obj is Person {
return obj && typeof obj === "object" && "name" in obj;
}
let person: Person | null = {
name: "John Doe",
};
if (isPerson(person)) {
// personはPerson型であることが保証される
const name = person.name; // 型安全にnameプロパティにアクセスできる
}
この方法は、変数の型を安全に確認するのに便利です。
// 1. == nullを使用する
let foo: string | null = "bar";
if (foo == null) {
console.log("fooはnullまたはundefinedです");
}
// 2. === nullと=== undefinedを使用する
foo = null;
if (foo === null) {
console.log("fooはnullです");
} else if (foo === undefined) {
console.log("fooはundefinedです");
}
// 3. オプションプロパティとnull合体演算子を使用する
interface Person {
name: string;
}
let person: Person | null = {
name: "John Doe",
};
const name = person?.name;
if (name) {
console.log(`nameは${name}です`);
} else {
console.log("nameはnullまたはundefinedです");
}
// 4. in演算子を使用する
person = null;
if ("name" in person) {
console.log("personはnameプロパティを持っています");
} else {
console.log("personはnameプロパティを持っていません");
}
// 5. 型ガードを使用する
function isPerson(obj: any): obj is Person {
return obj && typeof obj === "object" && "name" in obj;
}
person = {
name: "Jane Doe",
};
if (isPerson(person)) {
console.log(`nameは${person.name}です`);
} else {
console.log("personはPerson型ではありません");
}
fooはnullまたはundefinedです
fooはnullです
nameはJohn Doeです
personはnameプロパティを持っていません
nameはJane Doeです
TypeScriptでnullとundefinedをチェックするその他の方法
??演算子を使用する
let foo: string | null = null;
const name = foo ?? "デフォルトの名前";
console.log(name); // "デフォルトの名前"が出力される
typeof
演算子を使用して、変数の型をチェックすることができます。
let foo: string | null = null;
if (typeof foo === "undefined") {
// fooはundefined
} else if (typeof foo === "object" && foo === null) {
// fooはnull
}
let foo: string | null = null;
const name = foo ? foo : "デフォルトの名前";
console.log(name); // "デフォルトの名前"が出力される
typescript null-check