Item 32: Avoid Including null or undefined in Type Aliases

May 10, 2024 ยท View on GitHub

Things to Remember

  • Avoid defining type aliases that include null or undefined.

Code Samples

function getCommentsForUser(comments: readonly Comment[], user: User) {
  return comments.filter(comment => comment.userId === user?.id);
}

๐Ÿ’ป playground


type User = { id: string; name: string; } | null;

๐Ÿ’ป playground


interface User {
  id: string;
  name: string;
}

๐Ÿ’ป playground


type NullableUser = { id: string; name: string; } | null;

๐Ÿ’ป playground


function getCommentsForUser(comments: readonly Comment[], user: User | null) {
  return comments.filter(comment => comment.userId === user?.id);
}

๐Ÿ’ป playground


type BirthdayMap = {
  [name: string]: Date | undefined;
};

๐Ÿ’ป playground


type BirthdayMap = {
  [name: string]: Date | undefined;
} | null;

๐Ÿ’ป playground