티스토리 뷰

 

 

  • in 문법: 객체에 특정 속성이 존재하는지 확인할 때 사용된다.
  • typeof 문법: 변수의 타입을 확인할 때 사용된다

 

예제를 통해 알아보자.

 

 

 

1. in 문법


interface Person {
  name: string;
  age?: number;
}

const person: Person = {
  name: "Alice",
  age: 30,
};

console.log("age" in person); // true
console.log("address" in person); // false

 

 

 

 

2. typeof 문법


let x = "hello";
let y = 42;
let z = true;

console.log(typeof x); // "string"
console.log(typeof y); // "number"
console.log(typeof z); // "boolean"

 

 

 

 

3. intypeof를 함께 사용하여 객체의 속성 타입을 검사


interface Car {
  make: string;
  model: string;
  year?: number;
}

const car: Car = {
  make: "Toyota",
  model: "Camry",
  year: 2020,
};

if ("year" in car && typeof car.year === "number") {
  console.log(`The car was made in ${car.year}.`);
} else {
  console.log("Year information is not available.");
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함