TypeScript: Interface Ep.3

function interface


인터페이스로 함수 표현하기

  • 에러 발생

    function의 age 부분에 물음표를 제거해서 에러가 발생했다.

    interface HelloPerson {
      (name: string, age?: number): void;
    }
      
    const helloPerson: HelloPerson = function (name: string, age: number){
      console.log(`안녕하세요! {name} 입니다!`);
    }
    

    helloPerson function 뒤부터 적혀있는 실제로 구현한 내용보다는 (name: string, age:number 등) HelloPerson과의 관계가 더 중요하다.
    그렇기에 helloPerson의 age는 number만 HelloPerson의 age는 number, undefined를 포함하기에 둘 사이 관계가 맞지 않아서 에러가 발생하게 된다.

Readonly Interface Properties


인터페이스 property의 readonly 키워드 알아보기

readonly 키워드는 추후에 값을 변경하지 않게 하고 싶을 때 사용한다.
해당 키워드를 사용하게 되면 해당 값을 변경하게 되었을 때 에러가 발생한다.

readonly를 사용하게 되면 class에서도 readonly를 받아서 표현할 수 있기에 유용하다.

  • readonly 미사용

    p81의 gender을 변경해도 오류가 발생하지 않는다.

    interface Person8 {
      name: string;
      age?: number;
      gender: string;
    }
      
    const p81: Person8 = {
      name: 'Mark',
      gender: 'male',
    };
      
    p81.gender = 'female'
    
  • readnonly 사용

    p81의 gender를 변경하면 오류 발생한다.
    readonly 키워드를 사용했기 때문에 gender의 값을 변경해주면 오류가 발생하게 된다.

    interface Person8 {
      name: string;
      age?: number;
      readonly gender: string;
    }
      
    const p81: Person8 = {
      name: 'Mark',
      gender: 'male',
    };
      
    p81.gender = 'female'
    

type alias vs interface


  • function 표현
    • type alias

      type을 작성하고 뒤에 함수의 이름 작성한다.

      type EatType = (food: string) => void;
      
    • interface

      interface 선언 후, 함수의 형태를 넣는다.

      interface IEat {
        (food: string): void;
      }
      
  • array 표현
    • type alias

      string array([])표현을 한 다음에 이것을 어떠한 이름으로 부를 지 별칭 지정한다.

      type PersonList = string[];
      
    • interface

      indexable 타입을 사용한다.
      (이전에 배운 indexable 타입은 optional하게 사용하기 위해서 number가 아닌 string으로 사용했었다.)
      indexable 타입을 배열로 사용하려는 것이기에 index 뒤에 number사용 ( [0], [1] 이런식으로 표현 될 것이다.)하고 그 뒤에 string 값을 할당한다.

      interface IPersonList {
        [index: number]: string;
      }
      
  • intersection 표현

    interface ErrorHanding {
      success: boolean;
      error?: {message: string};
    }
      
    interface ArtistData {
      artists: {name: string}[];
    }
    
    • type alias

      ‘&’기호를 활용해서 type aliasing을 통해 intersection을 표현한다.

      type ArtistsResponseType = ArtistsData & ErrorHanding;
      
    • interface

      다중 상속 방식을 사용하여 intersection처럼 구성한다.

      interface IArtistsResponse extends ArtistsData, ErrorHanding {}
          
      let art: ArtistsResponseType;
      let iar: IArtistsResponse;
      
  • union types

    interface Bird {
      fly(): void;
      layEggs(): void;
    }
      
    interface Fish {
      swim: void;
      layEggs(): void;
    }
      
    type PetType = Bird | Fish;
      
    interface IPet extends PetType {}
      
    class Pet implements PetType {}
    
    • type alias

      사용으로 간단하게 union 타입 생성한다.
      type PetType = Bird | Fish;
      
    • interface

      인터페이스로는 union type을 만들 수 없다.

      interface IPet extends PetType {}
          
      class Pet implements PetType {}
      

      error! An interface cas only extends as objects type or intersection of object types with statically known members.

      error! class cas only extends as objects type or intersection of object types with statically known members.

  • interface - Declaration Merging

    type alias에서는 할 수 없는 기능으로 오직 interface만 가능하다.

    똑같은 이름의 interface를 두 군데에서 사용하더라도 나중에 MergingInterface를 사용 할 때에는 하나로 합쳐지게 된다. 즉 말 그대로 선언이 Merging 되는 것이다.

    mi.을 하게 되면 a와 b 모두 나오게 된다.

    type을 아래와 같이 선언하게 되면 동일한 이름으로 또 만들었다고 에러가 발생하게 된다.

    Declaration Merging 유용하게 사용할 때
    html element를 확장하게 될때, 기존에 있는 인터페이스에 추가를 하는 것이다. 이럴 때 기존에 있던 것과 새롭게 추가한 것 모두 사용을 해야 하기에 두 내용을 합쳐야 된다. 우리는 이와 같은 상황에서 유용하게 사용할 수 있다.

    interface MergingInterface {
      a: string;
    }
      
    interface MergingInterface {
      b: string;
    }
      
    let mi: MergingInterface;
    mi.
    

Comments