제공된 타입의 키를 추출하여 Union 유형으로 반환한다.
interface IUser {
name: string;
age: number;
address: string;
}
type UserKeys = keyof IUser; //"name" | "age" | "address"
typeof 연산자와 함께 사용하면 객체의 key값도 추출할 수 있다.
const user = {
name: 'John',
age: 20,
address: 'Seoul'
}
type UserKeys2 = keyof typeof user; //"name" | "age" | "address"
user는 타입이 아니라 "객체" 이기 때문에 먼저 typeof를 사용해서 객체의 type을 가져온 다음 keyof를 사용해서 키를 추출해야 한다.
enum도 객체와 비슷하기 때문에 typeof
, keyof
를 사용하면 키를 추출할 수 있다.
enum UserRole {
admin,
manager,
}
type UserRoleKeys = keyof typeof UserRole; //"admin" | "manager"