ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • typescript에서 typeof (with keyof)
    TypeScript 2023. 6. 10. 13:44

    typeof는 기존 자바스크립트에서 이미 제공되는 문법이다.

    타입스크립트에서도 역시 typeof를 사용할 수 있는데, 타입스크립트에서는 좀 더 확장된 기능들을 사용할 수 있다.

     

    기본적인 문법은 자바스크립트와 크게 다르지 않다.

    // typescript v5.0.4
    const str: string = "Hello type";
    type Str = typeof str; // string

    위와 같이 typeof로 타입을 타입 변수에 할당할 수 있다.

    물론, 변수에 할당하지 않고도 곧바로 타입으로 지정할 수도 있다.

    // typescript v5.0.4
    const str: string = "Hello type";
    const hello: typeof str = "Hi";

     

    그리고 타입스크립트에서 typeof의 중요한 기능중 하나로, typeof를 통해서 이미 존재하는 객체의 타입을 생성할 수 있다.

    객체를 생성과 동시에 할당하면, 타입 추론으로 타입스크립트가 알아서 객체의 타입을 지정해주는데 typeof를 통해서 이 객체의 타입을 재사용할 수 있다.

     

    // typescript v5.0.4
    const obj = {
      nicknmae: "parkend",
      created: 20230522,
    }
    
    type User = typeof obj;
    /*
    type User = {
      nicknmae: string;
      created: number;
    }
     */

     

    그렇다면, 객체가 내부에 또 다른 객체나 배열을 가질경우에는 어떨까?

    // typescript v5.0.4
    const obj = {
      nicknmae: "parkend",
      created: 20230522,
      friends: ['cheks', 'knightpark', 'chefjohn'],
      characters: {
        'warrior': 12,
        'magician': 46,
        'chef': 220
      },
    }
    
    type User = typeof obj;
    /*
    type User = {
        nicknmae: string;
        created: number;
        friends: string[];
        characters: {
            warrior: number;
            magician: number;
            chef: number;
        };
    }
    */

    이와 같은 경우에도 typeof가 훌륭하게 작동한 것을 확인할 수 있었다.

    내부에 프로퍼티로 배열이 있어도 배열의 타입을 잘 가져오며 객체가 있어도 객체의 타입을 정확하게 추론하여 가져올 수 있다.

     

    그렇다면 좀 더 복잡한 배열의 데이터는 어떨까?

    // typescript v5.0.4
    const obj = {
      etc: ['trash', 1, {tmp: 123}]
    }
    
    type Etc = typeof obj;
    /*
    type Etc = {
        etc: (string | number | {
            tmp: number;
        })[];
    }
     */

    위와 같이 여러 타입의 데이터를 지니는 배열의 경우에도, 유니온을 사용하여 데이터를 잘 표현하는 것을 알 수 있다.

     

    typeof는 keyof와도 함께 사용될 수 있다.

    자주 사용되는 패턴으로는 객체 변수에 keyof typeof를 함께 사용하여 key 값을 타입으로 가지는 타입을 생성하는 것이다.

    // typescript v5.0.4
    const obj = {
      nicknmae: "parkend",
      created: 20230522,
      friends: ['cheks', 'knightpark', 'chefjohn'],
      characters: {
        'warrior': 12,
        'magician': 46,
        'chef': 220
      },
    }
    
    type Keys = keyof typeof obj;
    /*
    type Keys = "nicknmae" | "created" | "friends" | "characters"
     */

     

    객체를 선언하면서 as const 키워드를 추가하면, 자동으로 생성한 객체를 readonly로 만들 수 있다.

    const obj = {
      nicknmae: "parkend",
      created: 20230522,
    } as const;
    
    type Obj = typeof obj;
    /*
    type Obj = {
        readonly nicknmae: "parkend";
        readonly created: 20230522;
    }
    */

     

    🍒 참고한 공식문서 자료 

    https://www.typescriptlang.org/docs/handbook/2/typeof-types.html#handbook-content

     

    Documentation - Typeof Type Operator

    Using the typeof operator in type contexts.

    www.typescriptlang.org

     

Designed by Tistory.