카테고리 없음

타입스크립트 - typeOf / keyOf

woody-j 2024. 1. 3. 21:30

typeOf / keyOf

1) typeOf

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

 

const fruitObj = {
one:'apple',
two:'pear',
three:'orange'
}

 

fruit은 객체이기에, 객체 자체를 타입으로 사용할 수 없다.

만약에 객체에 쓰인 타입구조를 그대로 가져와 독립된 타입으로 만든다면,

앞에 typeof 키워드 명시해주면 해당 객체를 구성하는 타입 구조를 가져와 사용가능하다.

 

const fruitObj = {
one:'apple',
two:'pear',
three:'orange'
}

type Fruit = typeof fruitObj;

/*
type Fruit = {
one:string,
two:string,
three:string
}
*/

 

함수도 타입으로 변환하여 재사용이 가능하다.

 

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

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

const ff: Fn_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,
};

 

2) keyOf

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

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 cucuber을 상수 타입으로 사용하고 싶다면 이렇게 아래와 같이 생성

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';

as const

객체 프로퍼티를 리터럴 타입으로 고정하는데 사용

일반적으로 객체의 문자열 값은 string, as const 사용 시 값이 해당 리터럴의 정확한 타입으로 고정

 

ex)

 

1) 일반적 객체 타입

const SIZE = {
  x-small: '1.6rem',
  small: '2.0rem',
  // ...
};

SIZE[x-small]는 단순히 string 타입으로 해석

->'1.6rem'이라는 구체적인 값보다 더 넓은 범위의 문자열을 나타냄

 

2) as const 사용시의 타입

const SIZE = {
  x-small: '1.6rem',
  small: '2.0rem',
  // ...
} as const

 

-> SIZE[x-small]는 '1.6rem' 이라는 구체적인 문자열 리터럴 타입을 가짐 : 문자열 값 외에는 다른 어떤 값도 할당 못함

 

왜 사용하는가?

  • 타입 안정성: 객체의 프로퍼티 값이 불변임을 보장하여, 코드의 다른 부분에서 해당 값이 예상대로 사용될 것임을 확신할 수 있다
  • 자동 타입 추론: 객체의 프로퍼티 값을 수정하거나 추가할 때마다 매번 타입을 수동으로 업데이트할 필요가 없어집니다. 타입스크립트가 자동으로 정확한 타입을 추론한다.
  • 코드 가독성: 코드를 읽는 사람은 as const를 통해 해당 객체의 값이 변경되지 않을 것임을 쉽게 이해할 수 있다.

 

https://inpa.tistory.com/entry/TS-%F0%9F%93%98-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-keyof-typeof-%EC%82%AC%EC%9A%A9%EB%B2%95