Language/TypeScript
[TS] Syntax | 07. keyof & typeof
Rayi
2024. 7. 10. 20:35
keyof는 딕셔너리 형태로 선언되어 있는 객체의 key값을 반환하는 키워드입니다.
이를 이용하면 interface 타입과 같이 여러 타입으로 구성되어 있는 타입의 각 요소들을 쉽게 사용할 수 있습니다.
interface Character {
id: string;
name: string;
price: number;
membersOnly?: boolean;
}
// 다음과 같은 코드를
type characterProperty = 'id' | 'name' | 'hp' | 'mp';
// keyof를 사용해서 간단하게 나타낼 수 있습니다.
type characterProperty = keyof Character;
typeof는 대상 변수의 타입을 반환하는 키워드입니다.
JS의 typeof는 타입을 문자열로 반환하지만, TS의 typeof는 타입 자체를 반환한다는 차이가 있습니다.
const redMage: Character = {
id: '001',
name: 'mage',
hp: 100,
mp: 50,
};
// redMage의 타입인 Character를 받아옵니다.
const blueMage: typeof redMage;
보통 특정 객체의 하위값들을 모두 불러올 때 이 keyof와 typeof를 같이 쓰는 경우가 많습니다.
// redMage의 타입인 Character에서 key 값인 id | name | price | membersOnly를 가져옵니다.
type mageType = keyof typeof redMage;
단, typeof는 배열이나 null 등의 특별한 타입은 표현할 수 없습니다.
배열의 경우 Array.isArray( )를 사용하며, null은 단순한 비교연산으로 처리할 수 있습니다.
const A = [1, 2, 3];
console.log(Array.isArray(A)); // true
console.log(A === null); // false
제일 일반적인 범위에서는 instanceof( ) 를 사용합니다.
class Chair {}
const test = new Chair();
console.log(test instanceof Chair); // true
728x90