keyof / typeof 에대해서 ( + in , instanceof )

keyoftypeofkeyof/typeof참조


Typeof

아래와 같이 데이터를 타입으로 변환해주는 연산자


일반 데이터 → 일반 타입으로 변환

객체 데이터 → 객체의 타입으로 변환

메서드 → 메서드의 타입으로 변환

클래스 → 클래스의 타입으로 변환


일반데이터를 일반타입으로 변환

타입가드로 사용됨

const name = 'kim'

// typeof name은 string을 반환한다
if (typeof name === 'string') {
  console.log('이것은 string타입입니다');
}


객체를 타입으로 전환한 예제

예를 들면 아래의 1번을 2번으로 변환 ( 2번을 보면 한번에 알수있음 )

// 1
const obj = {
   red: 'apple',
   yellow: 'banana',
};

type Fruit = typeof obj;
// 2
/*
type Fruit = {
    red: string;
    yellow: string;
}
*/

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


메서드를 타입으로 전환한 예제

// 1
function fn(num: number, str: string): string {
   return num.toString();
}

type Fn_Type = typeof fn;
// 2
/* type Fn_Type = (num: number, str: string) => string */

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


클래스를 타입으로 전환한 예제

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

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

const cc: Class_Type = {
   name: '이름',
   age: 20,
};



Keyof

아래와 같이 타입으로 변환해주는 연산자


객체의 타입 → 객체의 키값을 Union타입으로 변환


객체의 타입을 키값의 Union으로 변경하는 예제

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

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


keyof 와 typeof가 같이 사용된 예제

객체의 데이터 → 객체의 타입 → 객체의 키값을 Union타입으로 변경하는 예제

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

// typeof가 먼저 적용되어 { red: string, yellow: string }
// 그 다음 keyof가 적용 되어 red | yellow가 된다
// 그러므로 type Color는 red | yellow이다
type Color = keyof typeof obj; 


제네릭에서 keyof가 사용된 예제

예를들어서 아래의 상황은 이와 같다

첫번째 인수는 객체가 들어가고

두번째 인수는 첫번째 인수의 객체의 키값이 들어가야하는 경우다

( 예를들어 해당 키값의 데이터를 출력하는 함수를 사용한다고 하면 아래와 같이 사용된다 )

function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}

let x = { a: 1, b: 2, c: 3, d: 4 };

getProperty(x, "a"); // 성공
getProperty(x, "m"); // 오류: 인수의 타입 'm' 은 'a' | 'b' | 'c' | 'd'에 해당되지 않음


instanceof

해당 객체가 특정 클래스의 생성자인지 확인하는 연산자

class User {}
const person = new User();
console.log(person instanceof User); // true


in

객체가 특정 키를 가지고 있는지 확인

let myObject = { name: "John", age: 30 };
console.log("name" in myObject); // true
console.log("email" in myObject); // false


정리

  • typeof 데이터 → 타입 ( 데이터를 타입으로)

  • keyof 객체타입 → key값 추출후 union타입으로 변경 (객체 타입의 키값을 유니온 타입으로)


참조

keyof와 typeof에대해 굉장히 잘 정리한 사이트

in과 instanceof에 대해서

Mar 28, 2024 Views 65