타입스크립트 null과 undefined 예제

타입스크립트( Typescript )에서 null과 undefined는 모두 값이 없음을 뜻한다.

다만, null과 undefined의 의미에는 차이가 있습니다.

null은 개발자가 의도적으로 값이 비어 있음을 지정할 때 사용하지만, undefined는 변수나 속성에 아직 값이 할당되지 않았음을 뜻한다.

두 타입의 차이를 알고 있다면, 값의 존재 여부를 정확하게 확인하고, 조건문이나 함수의 반환값을 처리할 때 발생할 수 있는 오류도 줄일 수 있습니다.

let username: string | undefined;

console.log(username);
// undefined

interface User {
  name: string;
  phone?: string;
}

const user: User = {
  name: "민수",
};

console.log(user.phone);
// undefined

let selectedUser: string | null = null;

selectedUser = "민수";

let profileImage: string | null = null;

interface Profile {
  nickname: string;
  introduction: string | null;
  phone?: string;
}

const profile: Profile = {
  nickname: "코딩초보",
  introduction: null,
};

댓글

이 블로그의 인기 게시물

ChatGPT Codex GitHub 연결 해제 방법 (앱 삭제까지 정리)

C언어 return 종류와 차이 | return, return 0, return -1, return n

챗지피티 코덱스와 깃허브 연동 방법 | VSCode 사용하기