🤖

interfaceのoptionalとnullableの違い

2025/02/02に公開

インターフェースにおいてプロパティがオプショナルの時、
・プロパティごと渡さない
or
・undefinedを明示的に渡す

interface Person {
    name: string;
    age?: number; // オプショナルなプロパティ
}

const person1: Person = {
    name: "Alice"
};

const person2: Person = {
    name: "Bob",
    age: undefined // undefinedは設定できるがnullはNG
};

プロパティの値がnullableなときは、nullを明示的に渡す

interface Book {
    title: string;
    author: string | null; // authorは文字列またはnull
}

const book1: Book = {
    title: "Example Book",
    author: null // 注意:プロパティが無いとコンパイルエラー
};

Discussion