TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property (타입스크립트는 타입 컨텍스트에서 변수나 프로퍼티의 타입을 나타내기 위해 타입 컨텍스트에서 사용할 수 있는 typeof 연산자를 추가합니다.)
typeof
연산자가 존재하는데, 타입을 사용하는 환경에서 typeof
연산자를 사용하면 이를 타입으로 나타낼 수 있다.let s = "hello"; // s의 타입은 string
// string이라고 표기하지 않고 typeof s로도 표현할 수 있다.
let n: typeof s = "world";
const fruit = {
red: 'apple',
yellow: 'banana',
purple: 'grape'
}
// 객체인 fruit의 프로퍼티를 전체를 타입으로 사용하겠다고 선언
type Fruit = typeof fruit
// 즉 다음과 같다.
type Fruit {
red: string,
yellow: string,
purple: string
}
// fruit 객체와 똑같은 key명과 타입으로 프로퍼티를 생성해야만 한다.
const fruit2: Fruit = {
red: 'cherry',
yellow: 'lemon',
purple: 'plum'
}
The keyof operator takes an object type and produces a string or numeric literal union of its keys. (keyof 연산자는 객체 타입을 받아 객체의 key들로 구성된 문자열 또는 숫자 유니온 타입을 생성합니다.)
keyof
연산자는 객체 타입의 프로퍼티 key를 유니온 타입으로 구성해주는 연산자이다.// 객체 타입
type fruit = {
red: 'apple',
yellow: 'banana',
purple: 'grape'
}
// 객체 타입의 프로퍼티 key로만 구성 -> 'red' | 'yellow' | 'purple'과 동일
type Color = keyof fruit
const fruitOne: Color = 'red'
const fruitTwo: Color = 'yellow'
const fruitThree: Color = 'purple'
// KR, JP보다는 알아보기 쉬운 이름으로 key명을 지어주면 해당 key로 값에 접근할 수 있다.
const countryCode = {
korea: 'KR',
japan: 'JP'
} as const
// typeof는 실제 객체를 객체 타입으로 변환해주고,
// keyof는 변환된 객체 타입의 key를 유니온 타입으로 변환해준다.
type Type = keyof typeof countryCode
const 김코딩의_국적: Type = 'korea'
const 박해커의_국적: Type = 'japan'
const countryCode = {
korea: 'KR',
japan: 'JP'
} as const
type Type = typeof countryCode[keyof typeof countryCode]
const 김코딩의_국적: Type = countryCode.korea
const 박해커의_국적: Type = countryCode.japan
typeof
연산자로 각각의 객체 전체를 객체 타입으로 만들어 내보내준다.이 방식은 'styled components에서 typescript 사용하기' 와 같이 구글링했을 때 나오는 일반적인 방식이었던걸로 기억한다. 처음 타입스크립트를 사용해 개발할 때는 해당 개념들이 와닿지 않았는데, 다시 공부하고 실제 나의 프로젝트로 돌아와 다시 확인해보니 이제는 이해가 된다.
keyof
연산자를 사용해 key를 유니온 타입으로 만들었다.타입스크립트에서 코드상수 객체를 통한 코드 타입 만들기!