본문으로 건너뛰기
yceffort
PostsSeriesTagsAbout🧪 Research
EN

Tweaks

theme
accent palette
film grain
minimal mode
BACK TO INDEX
◆ ESSAY
--min
--year
KOoriginal

mailMail icongithubtwitter
yceffort
•
© 2026
•
https://yceffort.kr
BACK TO INDEX
◆ ESSAY

Typescript, 객체의 키와 값 타이핑하기

avatar
yceffort
2021-05-27 · 2분
2min
2021year
KOoriginal
typescript
const object = {
  a: 'a',
  b: 'b',
  c: 'c',
}

const value = 'a'

const values = Object.values(object) // a, b, c
const isValid = values.includes(value) // true

if (!isValid) {
  throw new TypeError(`${value} is not one of values, ${values`)
}

위 코드에서, value가 a b c 중 하나가 아니면 에러가 날 것이다. 이를 타입스크립트에서 타입 가드를 하는 방법을 살펴보자.

typescript

const object = {
  a: 1,
  b: 2,
  c: 3,
}

type objectShape = typeof object

여기서 objectShape는 아래와 같을 것이다.

type objectShape = {
  a: number
  b: number
  c: number
}

여기에 as const 를 추가해보자.

const object = {
  a: 1,
  b: 2,
  c: 3,
} as const

type objectShape = typeof object
type objectShape = {
  readonly a: 1
  readonly b: 2
  readonly c: 3
}

두가지가 바뀐 것을 볼 수 있다. 첫번째로, 모든 속성에 readonly가 붙어서 객체의 키 값을 바꿀 수 없게 되었고 두번째로는 string이 었던 값이 정확히 값으로 바뀌게 되었다. 이는 모두 readonly로 값이 수정되지 않는 다는 것을 확실히 했기 때문이다.

이번엔 키를 추출해보자.

type keys = keyof objectShape // "a" | "b" | "c"

이러한 키를 추출했으니, 값들도 추출해 낼 수 있다.

type values = objetShape[keys] // 1 | 2 | 3

Valueof Generic

type objectShape = typeof object
type keys = keyof objectShape
type values = objectShape[keys]

이번엔 제네릭으로 돌아가보자.

type values = Shape[keyof objectShape]
type ValueOf<T> = T[keyof T]
const object = {
  a: 1,
  b: 2,
  c: 3,
}

type ValueOf<T> = T[keyof T]
const a: ValueOf<typeof object> = 1
const b: ValueOf<typeof object> = 2
const c: ValueOf<typeof object> = 3
const d: ValueOf<typeof object> = 4 // error Type '4' is not assignable to type 'ValueOf<{ readonly a: 1; readonly b: 2; readonly c: 3; }>

관련 글

  • #typescript#oxc#eslint

    typescript@7을 설치하면 벌어지는 일들: 블로그 모노레포 마이그레이션 기록

    pnpm lint가 12분 32초 걸리던 모노레포에 typescript 7.0.2를 넣어봤다. 타입체크는 조용히 지나갔는데 next build가 깨졌고, lint는 크래시했다. eslint와 prettier를 oxlint와 oxfmt로 갈아탄 하루의 연쇄 반응과 전후 실측 기록. 미리 말해두면, 빌드는 빨라지지 않았다.

    2026-08-10·17분
  • #typescript#backend

    Effect 시스템 심층 분석: 모나드에서 Algebraic Effects까지, 그리고 Effect-TS의 선택

    Effect-TS가 대체 뭔데 다들 난리인지 직접 파헤쳐봤다.

    2026-02-20·41분
  • #typescript

    TypeScript에서 switch문의 모든 케이스를 빠짐없이 처리했는지 검사하는 방법

    never 타입을 활용한 exhaustive check 패턴

    2026-01-17·13분
  • #react#typescript

    useEvent에서 useEffectEvent까지: React의 이벤트 핸들러 안정화 여정

    3년 전 RFC가 드디어 빛을 보다

    2025-12-15·24분

새 글을 놓치고 싶지 않으시다면 RSS로 구독해 주세요.

RSS 구독 →

yceffort — 프론트엔드 엔지니어입니다. 발표·기술 자문·기고 문의는 이곳에서 받고 있습니다.

← Back to the blogIssue on GitHub →