[javascript] 동적으로 생성된 프로퍼티의 타입 제한하기
동적으로 속성이 추가되는 JavaScript 객체를 다룰 때, 해당 속성의 타입을 제한하는 방법이 필요할 수 있습니다. 이러한 상황에서 타입 가드(Type Guards) 와 타입 단언(Type Assertion) 을 사용하여 원하는 동작을 구현할 수 있습니다.
타입 가드 (Type Guards)
타입 가드는 특정 타입의 값이 어떤 타입으로 평가될지를 판단하는 런타임 체크 로직을 말합니다.
function isPerson(obj) {
return obj && typeof obj.name === 'string';
}
const person = { name: 'Alice', age: 30 };
if (isPerson(person)) {
console.log(`${person.name} is a person`);
} else {
console.log('Not a person');
}
이 예시에서 isPerson
함수는 객체가 Person
형식인지를 확인하는 타입 가드입니다.
타입 단언 (Type Assertion)
타입 단언은 TypeScript 컴파일러에게 컴파일 시간에 변수의 타입을 알려주는 기능입니다.
interface Car {
model: string;
year: number;
}
const myCar: any = { model: 'Tesla', year: 2022 };
const formattedCar = myCar as Car;
console.log(`My car is a ${formattedCar.year} ${formattedCar.model}`);
위의 예시에서 myCar
변수는 any
타입으로 선언되어 있습니다. 하지만, formattedCar
변수에 타입 단언을 사용하여 Car
인터페이스를 적용하여 타입을 제한했습니다.
결론
JavaScript에서 동적으로 생성된 프로퍼티의 타입을 제한하기 위해서는 타입 가드와 타입 단언을 사용할 수 있습니다. 이러한 방법을 사용하면 코드의 안정성과 가독성을 높일 수 있습니다.
참고자료:
- 타입 가드(Type Guards): MDN Web Docs - User-Defined Type Guards
- 타입 단언(Type Assertion): TypeScript Handbook - Type Assertions
원문
Restricting the Type of Dynamically Created Properties