null과 undefined는 공집합?

이연중·2021년 12월 2일
0

TypeScript

목록 보기
4/4

프로젝트를 하던 중 인터페이스로 타입을 선언하는 과정에서 null 타입도 아니고 유니언 타입으로 null을 포함해주지도 않았는데 null 값을 넣었을 때 오류가 나지 않는 것을 보고 의아해 했었다.

바로 구글링에 들어갔고, 도움이 되는 정보를 얻을 수 있었다.

null, undefined like 공집합?


기본적으로 모든 타입은 null과 undefined를 포함한다고 한다.(default. 자동으로)

//예시
const num: number= null				//OK
const str: string= undefined			//OK
...

마치, 집합들은 항상 부분집합으로 공집합을 가지는 것과 같다고 생각했다.


null, undefined가 포함되지 않게 하는 방법


자동으로 null과 undefined를 포함하지 않으려면?
strictNullChecks를 설정해주면 된다고 한다.

Where?
tsconfig.jsoncompilerOPtions 부분에 있는 strictNullCheckstrue로 해주면 된다고 한다.

//tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,			//true로 변경!!
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

결론


타입스크립트에서 기본적으로 모든 타입들은 null, undefined를 포함한다!

profile
Always's Archives

0개의 댓글