Null vs Undefind
용어설명
1. undefiend
- 어떠한 값도 할당되지 않아 자료형이 정해지지 않은 상태입니다.
2. null
- 자료형이 정해진(defined) 상태입니다.
- null 값이 할당된 상태입니다.
Null 과 Undefined 코드로 비교하기
console.log(null == null); // true
console.log(undefined == undefined); // true
console.log(null == undefined); // true
console.log(null === null); // true
console.log(undefined === undefined); // true
console.log(null === undefined); // false
null == undefined 결과가 true이기 때문에 작성 가능한 코드
const foo = (arg: string | null | undefined) => {
if (arg == null) {
// null 또는 undefined 값이 매개변수로 들어왔습니다.
} else {
console.log(arg);
}
}
Null 과 Undefined 어떤걸 사용해야 하지?
Typescript 공식 문서를 보면 아래와 같이 나와 있습니다.
undefined 를 사용하고 null 을 사용하지 마세요.
null 을 사용하지말고 undefined 를 사용하라고 하는 문서
Coding guidelines · microsoft/TypeScript Wiki
GitHub - microsoft/TypeScript: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output. - GitHub - microsoft/TypeScript: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
github.com
null 은 나쁜 아이디어!
알고 있으면 좋은 점 ( 근데 주관적인 생각도 좀 들어간… )
undefined 를 명시적으로 선언해주는것은 좋지 않습니다.
undefined는 변수는 존재하나, 어떠한 값도 할당되지 않은 상태라는 말 입니다.
의도적으로 undefined 를 선언해서 사용하는것은 옳지 않습니다.
의도적으로 undefined 값을 주는것 이라면 차라리 null 을 주는것이 낫다고 생각합니다.
하지만 더 좋은 방법은 그냥 값을 주지 않는것이죠.
어차피 참조하려고 하면 undefined를 자동으로 뱉을테니까요.
const badItem = { a: 1, b: undefined }; // bad
const goodItem = { a: 1 }; // good
참조 페이지 :
https://basarat.gitbook.io/typescript/
README - TypeScript Deep Dive
Share URL: https://basarat.gitbook.io/typescript/
basarat.gitbook.io