[TypeScript] typeof 타입 연산자

typeof의 확장

JavaScript에서의 역할

JavaScript에서 `typeof`는 값의 런타임 타입을 문자열로 알려줍니다

console.log(typeof "안녕"); // 출력: "string"

TypeScript에서의 역할

TypeScript는 이를 확장해 타입 컨텍스트에서 사용 가능하게 했습니다. 그래서 정적 타입 검사에 활용할 수 있습니다.

기본 타입에서의 사용

const score = 95;
let grade: typeof score; // number

grade = 88;
// grade = "A"; // 오류: string은 number에 할당 불가

typeof와 ReturnType의 조합

`typeof`는 함수의 반환 타입을 가져오는 데 유용하며, `ReturnType`과 함께 사용하면 더욱 강력합니다.

ReturnType

ReturnType은 함수의 반환 타입을 추출하는데 사용됩니다.

function getStatus() {
  return { active: true, time: 100 };
}

type StatusType = ReturnType<typeof getStatus>; // { active: boolean; time: number }

const status: StatusType = { active: false, time: 200 };
console.log(status.active, status.time); // 출력: false 200

복잡한 객체에서의 typeof

const profile = {
  id: "user123",
  name: "하영",
  verified: true as const,
};

type ProfileType = typeof profile; // { id: string; name: string; verified: true }

const updateProfile = (data: ProfileType): void => {
  console.log(`ID: ${data.id}, Name: ${data.name}, Verified: ${data.verified}`);
};

updateProfile({ id: "user456", name: "민수", verified: true });
// 출력: ID: user456, Name: 민수, Verified: true

keyof와 typeof의 결합

const config = {
  host: "localhost",
  port: 8080,
};

type ConfigKeys = keyof typeof config; // "host" | "port"

function getConfigValue(key: ConfigKeys, obj: typeof config): string | number {
  return obj[key];
}

console.log(getConfigValue("host", config)); // 출력: localhost
console.log(getConfigValue("port", config)); // 출력: 8080