ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Typescript] type과 Interface
    Frontend/Typescript 2023. 3. 12. 16:13

    TypeScript에서 타입(Type)과 인터페이스(Interface)는 유사한 점이 매우 많고, 여러 경우에 자유롭게 혼용되어 사용 가능합니다.

    interface AnimalInterface {
      species: string
      height: number
      weight: number
    }
    
    const tiger: AnimalInterface = {
      species: 'tiger',
      height: 200,
      weight: 300
    }
    
    type AnimalType = {
      species: string,
      height: number,
      weight: number
    }
    
    const lion: AnimalType = {
      species: 'lion',
      height: 180,
      weight: 400
    }
    

    하지만 둘의 차이와 한계를 이해하고 표준화해 사용하는 것이 매우 중요합니다.

    공식문서에서 특별한 경우를 제외하고 type보다 interface 사용을 권장!

    따라서 저는 interface 위주로 정리하겠습니다.

    확장하는 방법(상속)

    interface AnimalInterface {
      species: string
      height: number
      weight: number
    }
    
    interface AfricaAnimal extends AnimalInterface {
      continent: string
    }
    

    interface는 extends로 확장

    type AnimalType = {
      species: string,
      height: number,
      weight: number
    }
    
    type AfricaAnimal = AnimalInterface & {
      continent: string
    }
    

    type은 &로 확장

    선언적 확장

    interface는 선언적 확장이 가능합니다.

    type은 새로운 속성을 추가하기 위한 선언적 확장이 불가능합니다.

    interface Animal {
      weight: number;
    }
    
    interface Animal {
      height: number;
    }
    
    const tiger: Animal = {
      weight: 100,
      height: 200,
    };
    console.log(tiger);
    
    type _Animal = {
      weight: number;
    };
    
    type _Animal = {//error : 식별자가 중복됨
      height: string;
    };
    

    interface는 객체에만 사용 가능

    // 객체 타입 선언 가능
    type AnimalType = {
      name: string
    }
    //리터럴 타입 선언 가능
    type AnimalOnlyString = string
    
    // 객체만 선언 가능
    interface AnimalInterface {
      name: string
    }
    
    //리터럴 타입으로 확장 불가능
    interface AnimalInterface extends string {} //error
    

    computed value 사용

    type만 가능

    type names = 'firstName' | 'lastName'
    
    type NameTypes = {
      [key in names]: string
    }
    
    const yc: NameTypes = { firstName: 'hi', lastName: 'yc' }
    
    interface NameInterface {
      // error
      [key in names]: string
    }
    

    type VS interface 확장시 성능 비교

    결론부터 말씀드리면 interface가 훨씬 좋습니다.

    interface는 확장시 속성간 충돌을 피하기 위해 단순한 객체 타입을 만듭니다. 왜냐하면 interface는 객체만 오기 때문에 단순히 합치기만 하면 되기 때문입니다.

    하지만 type은 재귀적으로 순회하면서 속성을 merge하는데, interface와 다르게 type은 원시 타입이 올수도 있으므로 충돌이 나서 제대로 merge되지 않을 수 있습니다.

    또한, interface를 합성할 경우 이는 캐시가 되지만, type은 그렇지 않습니다.

    type은 합성에 대한 유효성을 판단하기 전에 모든 구성요소에 대한 type을 체크하기 때문에 컴파일 시에 상대적으로 성능이 좋지 않습니다.

     

    https://betterprogramming.pub/differences-between-type-aliases-and-interfaces-in-typescript-4-6-6489246d4e48

     

    Differences Between Type Aliases and Interfaces in TypeScript 4.6

    Type aliases and interfaces are very similar, so which one should I use?

    betterprogramming.pub

     

    'Frontend > Typescript' 카테고리의 다른 글

    [Typescript] Type Guard  (0) 2023.03.12
    [Typescript] Enum  (0) 2023.03.12
    [TypeScript] 잘 사용하기  (0) 2023.02.19
    [TypeScript] 동작 원리, 장점과 단점  (0) 2023.02.19

    댓글

Designed by Tistory.