[TS] keyof 연산자

김다빈·2023년 9월 4일
0

타입스크립트

목록 보기
13/13
post-thumbnail

📌 keyof 연산자

제공된 타입의 키를 추출하여 Union 유형으로 반환한다.

interface IUser {
  name: string;
  age: number;
  address: string;
}

type UserKeys = keyof IUser; //"name" | "age" | "address"

✅ keyof typeof 객체

typeof 연산자와 함께 사용하면 객체의 key값도 추출할 수 있다.

const user = {
  name: 'John',
  age: 20,
  address: 'Seoul'
}

type UserKeys2 = keyof typeof user; //"name" | "age" | "address"

user는 타입이 아니라 "객체" 이기 때문에 먼저 typeof를 사용해서 객체의 type을 가져온 다음 keyof를 사용해서 키를 추출해야 한다.

✅ keyof typeof enum

enum도 객체와 비슷하기 때문에 typeof, keyof 를 사용하면 키를 추출할 수 있다.

enum UserRole {
  admin,
  manager,
}

type UserRoleKeys = keyof typeof UserRole; //"admin" | "manager"
profile
Hello, World

0개의 댓글

관련 채용 정보