keyof
let product2: typeof product; // Product타입
console.log(typeof product) // object 라는 문자열 출
interface Product {
id: string;
name: string;
price: number;
membersOnly?: boolean;
}
type ProductProperty = 'id' | 'name' | 'price' | 'membersOnly';
const productTableKeys: ProductProperty[] = ['name', 'price', 'membersOnly'];
const product: Product = {
id: 'c001',
name: '코드잇 블랙 후드 집업',
price: 129000,
membersOnly: true,
};
for (let key of productTableKeys) {
console.log(`${key} | ${product[key]}`);
}
Product 타입에 프로퍼티가 추가된다면
interface Product {
id: string;
name: string;
price: number;
membersOnly?: boolean;
salePrice: number; // 추가된 프로퍼티
}
type ProductProperty = 'id' | 'name' | 'price' | 'salePrice' | 'membersOnly'; // 수정
두 곳에서 수정을 해줘야한다. 오타도 나기 쉽다.
keyof 연산자를 사용하면 코드를 간단히 적고 유지보수성을 높일 수 있다.
type ProductProperty = keyof Product;
// 또는 바로 적어줘도 된다
const productTableKeys: (keyof Product)[] = ['name', 'price', 'membersOnly'];
typeof
//타입스크립트 typeof
let product2: typeof product; // Product타입
//자바스크립트 typeof
console.log(typeof product) // object 라는 문자열 출력
'개발 공부 일지 > TypeScript' 카테고리의 다른 글
[한입 챌린지] 타입 스크립트 챌린지 회고 (0) | 2025.03.09 |
---|---|
타입스크립트 - 제네릭 (0) | 2024.09.13 |
타입스크립트 - Union, Intersection (0) | 2024.09.11 |
타입스크립트 - 리터럴 타입 / 타입 별칭 (0) | 2024.09.10 |
타입스크립트 - interface (0) | 2024.09.10 |