TypeScript

[Typescript] typeof 연산자 (with. JS에서의 typeof 연산자)

철스커 2023. 1. 7. 18:09
반응형
[ 목차 ]
JS에서의 typeof 연산자
TS에서의 typeof 연산자

 

JS에서의 typeof 연산자

자바스크립트에서도 typeof 연산자가 존재합니다.

어떤 값의 type을 string 형태로 반환하는 연산자입니다.

 

const a = typeof 1; // "number"
const b = typeof "str"; // "string"
const c = typeof false; // "boolean"
const d = typeof {}; // "object"
const e = typeof []; // "object"
const f = typeof function () {}; // "function"
const g = typeof null; // "object" -> 주의!
const h = typeof undefined; // "undefined"
const i = typeof Symbol(); // "symbol"

null의 타입은 object로 나오는데요.

잘 알려진 자바스크립트 오류 중 하나입니다...!

 

 

 

TS에서의 typeof 연산자

타입을 선언할 때 typeof 연산자를 사용하게 되면, 타입스크립트는 추론한 타입을 넣어줍니다.

 

const num = 777;
  const str = "str";
  const str2 = String(1);
  const obj = {
    name: "Rabbit",
    age: 10,
  };

  type Num = typeof num; // 777
  type Str = typeof str; // "str"
  type Str2 = typeof str2; // string
  type Obj = typeof obj; // { name: string, age: number }

 

반응형