ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • type vs interface
    Front-end/TypeScript 2021. 12. 21. 23:42

    named type을 지정할때 타입을 사용해도 되고 인터페이스를 사용해도된다. 

    타입과 인터페이스의 유사한 특징 

    1. 타입과 인터페이스에 정의되지 않은 속성을 추가하여 할당하면 오류가 발생한다.

    2.인덱스 시그니처 사용 가능 

    type Option = { [key: string]: string }
    interface Option {
      [key: string]: string | number | boolean 
     }

    3. 함수타입 정의 가능 

    type Func = (x: number) => string
    interface Func {
     (x: number) : string 
     }
     
     const toStr = Func = x => '' + x

    4. 제네릭 가능 

    5. 인터페이스는 타입을 확장할수 있고 타입도 인터페이스를 확장할 수 있다. 

    interface Member extends User {
      premium: boolean
    }
    type member = User & { premium: boolean }

    (인터페이스는 유니온 타입 같은 복잡한 타입을 확장하지 못한다. 타입과 &을 사용하여 확장 가능하다.) 

     6. 클래스 구현시 타입과 인터페이스 사용 가능

    class User implements IUser {
     premium: bollean = false
     gender: string = '' 
    }
    
    class User implements TUser {
     premium: bollean = false
     gender: string = '' 
    }

     

    타입과 인터페이스의 차이점 

    일반적으로 타입이 인터페이스보다 사용할 수 있는 범위가 넓다. 

    1. 유니온 타입은 있지만 유니온 인터페이스라는 개념은 없다.

    type AorB = 'a' | 'b'

     

    인터페이스는 타입을 확장할수 있지만, 유니온은 할 수 없다. 만약 유니온 타입을 확장하는게 필요하다면 아래와 같이 별도의 타입들을 하나의 변수명으로 매핑하는 인터페이스를 만들 수 있다. 

    interface VariableMap{
     [name: string] : Input | Output
     }

     

    또한 유니온 타입에 속성을 추가하여 타입을 만들 수 있으며 이러한 타입은 인터페이스로는 표현할수 없다. 

    type NamedVariable = ( Input | Output ) & { name: string }

     

    2. 튜플과 배열타입은 타입을 이용해 더 간결하게 표현할 수 있다. 

    type Pair = [number, number]
    type StringList = string[]
    type NamedNums = [string, ...number[]]

    인터페이스로도 튜플과 비슷하게 구현할수는 있으나 튜플에서 사용할수 있는 concat같은 메서드들을 사용할 수 없다.

    interface Tuple {
      0: number
      1: number
      length: 2
     }
     const t: Tuple = [10,20]

     

    3. 인터페이스에서는 필드 추가가 가능하다 (Merging interfaces) 

    The simplest, and perhaps most common, type of declaration merging is interface merging. At the most basic level, the merge mechanically joins the members of both declarations into a single interface with the same name. 

    interface User {
     gender: string
     nmae: string
    }
    
    interface User {
     email: string 
    }
    
    const user: User = { gender: 'female', name: 'madison', email: 'madison@ ~~~ ' }

     

    타입과 인터페이스 중 어느것을 사용해야 할까

    -리터럴하거나 상수는 type으로 , 객체는 interface로 ?  

    복잡한 타입일시 고민없이 타입을 사용해야한다. 만약 타입과 인터페이스로 표현할 수 있는 간단한 객체 타입이면 코드베이스에 따라서 선택하여 사용하면 된다. 일관되게 인터페이스를 사용하고 있다면 인터페이스를 사용하고 타입을 사용중이라면 타입을 사용하면 된다. 

     

     

     

    참고자료 : 

    https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces 

    effective typescript 

     

Designed by Tistory.