TIL77.keyof, typeof

조연정·2021년 3월 14일
1
post-thumbnail

keyof typeof를 유용하게 사용할 수 있는 예제에 대해 알아보자.

type of

1. typeof in js

자바스크립트는 변수의 데이터 타입을 반환하는 typeof 연산자가 존재한다.

const number =10;
console.log(typeof number)

// number

2. typeof in ts

타입스크립트는 변수 또는 속성의 유형을 참조하기 위해 typeof를 사용한다.

const str: string  = "hello";
const str2: typeof str;

// const str2: string

typeof keyof

기본유형보다는 다른 유형 연산자와 결합하여 typeof 여러 패턴을 편리하게 표현하는데 사용할 수 있다.

const score = {
  yes: 1,
  normal: 0,
  no:-1
}as const ;

//원하는 타입의 값
type ScoreType = 1 | 0 | -1;

// 1.typeof만 사용한 경우
type ScoreType = typeof score;
// 객체의 property를 추론
type ScoreType = {
    readonly yes: 1;
    readonly normal: 0;
    readonly no: -1;
}

// 2.keyof typeof 사용한 경우
type ScoreType = keyof typeof score;
// score의 키를 추론
type ScoreType = "yes" | "normal" | "no"

// 3.
type ScoreType = typeof score[keyof typeof score];
// score의 키 값을 추론
type ScoreType = 0 | 1 | -1

*as const

: 'score' 에 마우스를 올려보면 타입추론이 number로 나온다.
고정되어 있는 값, 상수처럼 쓰이기 때문에 as const를 사용하여 타입을 그 값 자체로 고정시킨다.

// as const x
const score: {
    yes: number;
    normal: number;
    no: number;
}

//as const o
const score: {
    readonly yes: 1;
    readonly normal: 0;
    readonly no: -1;
}
profile
Lv.1🌷

0개의 댓글