[TypeScript] keyof / typeof

정호·2023년 6월 2일
0

TIL

목록 보기
5/17

타입스크립트 - keyof / typeof


typeof 연산자

typeof : 객체 데이터를 객체 타입으로 변환해주는 연산자

아래의 obj객체이기 때문에, 당연히 객체 자체를 타입으로 사용할 수 없다.

그래서 만일 객체에 쓰인 타입 구조를 그대로 가져와 독립된 타입으로 만들어 사용하고 싶다면, 앞에 typeof 키워드를 명시해주면 해당 객체를 구성하는 타입 구조를 가져와 사용할 수 있다.

const obj = {
   red: 'apple',
   yellow: 'banana',
   green: 'cucumber',
};

// 위의 객체를 타입으로 변환하여 사용하고 싶을때
type Fruit = typeof obj;
/*
type Fruit = {
    red: string;
    yellow: string;
    green: string;
}
*/

let obj2: Fruit = {
   red: 'pepper',
   yellow: 'orange',
   green: 'pinnut',
};

함수도 타입으로 변환하여 재사용할 수 있다.

클래스는 자체가 객체이므로 typeof를 붙이지 않아도 됨 (인터페이스는 자체가 타입이라 불가능)

function example(num: number, str: string): string {
   return num.toString();
}

type Ex_Type = typeof example;
// type Ex_Type = (num: number, str: string) => string

const ff: Ex_Type = (num: number, str: string): string => {
   return str;
};

// --------------------------------------------------------------

class Classes {
   constructor(public name: string, public age: number) {}
}

type Class_Type = Classes;
// type Class_Type = { name: string, age, number }

const cc: Class_Type = {
   name: '임꺾정',
   age: 18888,
};

keyof 연산자

keyof : 객체 형태의 타입을, 따로 속성들만 뽑아 모아 유니온 타입으로 만들어주는 연산자

❖ 유니온 타입(Union Type)이란 자바스크립트의 OR 연산자(||)와 같이 A이거나 B이다 라는 의미의 타입

type Type = {
   name: string;
   age: number;
   married: boolean;
}

type Union = keyof Type;
// type Union = name | age | married

const a:Union = 'name';
const b:Union = 'age';
const c:Union = 'married';

obj 객체의 키값인 red, yellow, green을
상수 타입
으로 사용하고 싶을 때는 typeof obj 자체에 keyof 키워드를 붙여주면 된다.

const obj = { red: 'apple', yellow: 'banana', green: 'cucumber' } as const; // 상수 타입을 구성하기 위해서는 타입 단언을 해준다.

// 위의 객체에서 red, yellow, green 부분만 꺼내와 타입으로서 사용하고 싶을떄
type Color = keyof typeof obj; // 객체의 key들만 가져와 상수 타입으로

let ob2: Color = 'red';
let ob3: Color = 'yellow';
let ob4: Color = 'green';

apple, banana, cucumber을 상수 타입으로 사용하고 싶다면 다음과 같이 사용하면 된다.

const obj = { red: 'apple', yellow: 'banana', green: 'cucumber' } as const;

type Key = typeof obj[keyof typeof obj]; // 객체의 value들만 가져와 상수 타입으로

let ob2: Key = 'apple';
let ob3: Key = 'banana';
let ob4: Key = 'cucumber';
profile
열심히 기록할 예정🙃

0개의 댓글