Typescript

[Typescript] keyof, typeof

호박고구마123 2024. 9. 23. 23:59

keyof

정의

객체 타입의 키들을 유니언 타입으로 반환함. 객체의 모든 키를 타입 수준에서 다루고자 할 때 유용하게 사용

 

keyof 주의점

하지만 typeof를 사용할땐 주의점이 필요하다. 간혹 type에 사용하지 않고, const나 let과 같은 변수에 사용하는데, 이와 같은 경우에는 에러가 발생하므로 주의하자.

 

결론 : keyof는 변수 or 객체 리터럴에는 할당이 불가능함, type에만 할당가능함

 

type에만 할당 가능 예제1)

const obj = { a: 1, b: 2, c: 3,}; 
type TypeOfObj = typeof obj; // { a: number, b: number, c: number }
type Key = keyof typeof obj; // "a" | "b" | "c"

type에만 할당 가능 예제2)

type obj = { a: number, b: string};
type Key = keyof obj // "a" | "b"

변수 or 객체 리터럴의 할당 못하는 경우의 예제)

const obj = { a: 1, b: 2, c: 3,}; // const는 변수
type Key = keyof obj // X 오류 발생

typeof

정의

반적인 자바스크립트 변수의 런타임 타입을 반환하는 데 사용한다. 타입스크립트에서 변수나 객체의 타입을 추론하는 데 주로 사용한다.

일반적인 자바스크립트에서 사용

const numberValue = 42;
console.log(typeof numberValue); // "number"

타입스크립트에서의 사용

예제1)

const user = {
    username: "alice",
    email: "alice@example.com",
};

type UserType = typeof user; // { username: string; email: string; }\\

예제2)

const obj = { a: 1, b: 2, c: 3,}; 
type TypeOfObj = typeof obj; // { a: number, b: number, c: number }