- 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. in과 typeof를 함께 사용하여 객체의 속성 타입을 검사
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.");
}
'Client > TypeScript' 카테고리의 다른 글
[TypeScript] catch문 error 타입 정하기 (feat. 타입 가드와 타입 단언의 차이) (0) | 2024.06.19 |
---|---|
[TypeScript] keyof & typeof 연산자 (0) | 2024.05.31 |
[TypeScript] 타입스크립트의 배열 (0) | 2024.05.28 |
[TypeScript] 인덱스 시그니쳐 (0) | 2024.05.27 |
[TypeScript] TypeScript에서 클래스(Class) 사용하기 (0) | 2024.05.25 |