javascript

타입스크립트 키워드 정리 (typeof, keyof, keyof typeof, as const, Partial)

타입스크립트 핵심 문법 정리:

typeof,
keyof,
keyof typeof,
as const,
Partial

1. typeof

👉 값에서 타입을 뽑아오기

const age = 20;
type Age = typeof age; 
// number

const user = { name: "Tom", age: 20 };
type User = typeof user; 
// { name: string; age: number }

2. keyof

👉 객체 타입의 키를 유니온 타입으로 만들기

interface User {
  name: string;
  age: number;
}

type UserKeys = keyof User; 
// "name" | "age"

3. keyof typeof

👉 실제 객체에서 키를 타입으로 추출

const colors = { red: "#f00", green: "#0f0" };

type ColorKeys = keyof typeof colors; 
// "red" | "green"

function getColor(key: ColorKeys) {
  return colors[key];
}

getColor("red");   // ✅ OK
getColor("blue");  // ❌ Error

4. as const

👉 값과 타입을 리터럴로 고정

const fruit = "apple";
// 타입: string

const fruit2 = "apple" as const;
// 타입: "apple"

const fruits = ["apple", "banana"];
// string[]

const fruits2 = ["apple", "banana"] as const;
// readonly ["apple", "banana"]
// → "apple" | "banana" 로 타입 추출 가능

as const

  • 값을 변경 불가(readonly) 로 만들고,

  • 타입을 리터럴 그대로 좁혀줍니다.


5. Partial<T>

👉 모든 속성을 선택적(?)으로 바꾸기

interface User {
  name: string;
  age: number;
}

type PartialUser = Partial<User>;
// { name?: string; age?: number }

✅ 요약

  • typeof: 값 → 타입 변환

  • keyof: 타입의 키 추출

  • keyof typeof: 실제 객체 키를 타입으로

  • as const: 값 고정 → 리터럴 타입 + readonly

  • Partial: 모든 속성 선택적으로 변환

참조

https://chan-chan2.tistory.com/228