개념
TypeScript에서 in 연산자는 객체에 특정 속성이 존재하는지 확인하는 데 사용됩니다. 이는 자바스크립트의 in 연산자와 동일한 방식으로 작동하며, 객체의 프로토타입 체인에서도 속성을 확인합니다.
예시
in 연산자의 사용을 이해하기 위해 간단한 예제를 살펴보겠습니다.
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30
};
if ('name' in person) {
console.log("Name exists in person");
}
if ('address' in person) {
console.log("Address exists in person");
} else {
console.log("Address does not exist in person");
}
이 예제에서는 person 객체에 name 속성이 있는지 확인하고, 존재하면 "Name exists in person"을 출력합니다. address 속성은 존재하지 않기 때문에 "Address does not exist in person"을 출력합니다.
타입 가드로서의 사용
in 연산자는 TypeScript에서 특정 타입의 속성이 객체에 존재하는지 확인하는 타입 가드로서도 유용합니다. 이를 통해 TypeScript 컴파일러가 조건부 블록 내에서 객체의 타입을 좁히는 데 도움을 줍니다.
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
function getAnimal(): Bird | Fish {
// Some logic to return either a Bird or a Fish
return { fly: () => {}, layEggs: () => {} }; // 예제이므로 단순화된 반환
}
const pet = getAnimal();
if ('fly' in pet) {
pet.fly(); // 컴파일러는 pet이 Bird 타입임을 알게 됩니다.
} else {
pet.swim(); // 컴파일러는 pet이 Fish 타입임을 알게 됩니다.
}
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing
Documentation - Narrowing
Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects.
www.typescriptlang.org
'IT > typescript' 카테고리의 다른 글
[typescript] pnpm monorepo에서 paths 설정하기 (1) | 2024.07.15 |
---|---|
[typescript] is (1) | 2024.06.12 |
[typescript] as const (0) | 2024.06.03 |
[clean code] 놓치기 쉬운 것들 (0) | 2024.04.22 |
[typescript] Union & Intersection (1) | 2024.03.17 |