TypeScript: Interface Ep.2

function in interfaces


Interface안에서 함수를 정의하고 함수를 만들어서 사용 하기

interface Person4 {
  name: string;
  age: number;
  hello(): void;
}
  • function 키워드를 이용해서 함수를 만든 후, 해당 함수를 hello 변수에 할당

    const p41: Person4 = {
      name: 'Mark',
      age: 39,
      hello: function (): void {
        console.log(`안녕하세요! ${this.name}입니다.`)
      },
    }
    
  • function 키워드 없이 함수 만들기

    const p42: Person4 = {
      name: 'Mark',
      age: 39,
      hello(): void {
        console.log(`안녕하세요! ${this.name}입니다.`)
      },
    }
    
  • 화살표 함수로 만들기 → 사용 불가능

    단, 해당 방법은 오류 발생! 화살표 함수 내부에서는 this 사용이 불가능하다.

    const p43: Person4 = {
      name: 'Mark',
      age: 39,
      hello: () void => {
        console.log(`안녕하세요! ${this.name}입니다.`)
      },
    }
    

class implements interface


Interface를 이용해서 class 만들기

  • implements 키워드

    해당 키워드를 사용해서 interface를 class로 사용한다.
    interface의 내용을 바탕으로 class를 생성하는 것이다.
    해당 클래스는 인터페이스의 구성을 만족하는 형태로 만들어야 한다.

    interface IPerson1 {
      name: string;
      age?: number;
      hello(): void;
    }
      
    class Person implements IPerson1 {
      name: string;
      age?: number | undefined; 
      
      constructor(name: string) {
        this.name = name;
      }
      
      hello(): void {
        console.log(`안녕하세요! ${this.name}입니다.`)
      }
      
    }
      
    const person = new Person("Mark");
    // const person: IPerson1 = new Person("Mark");
    

    person을 확인하면 class Person이라고 나온다. 그런데 해당 Person은 interface IPerson1이 implement되어서 만들어진 것이기 때문에 주석 부분의 코드처럼 작성해도 된다.

interface extends interface


존재하는 interface를 가져와서 추가 interface를 넣기. 즉 상속이다!

IKorean은 IPerson2를 상속받았기 때문에 IPerson2가 가지고 있는 내용을 기본적으로 가지게 된다.

interface IPerson2 {
  name: string;
  age?: number;
}

interface IKorean extends IPerson2 {
  city: string;
}

const k: IKorean = {
  name: "Mark",
  city: "Seoul",
}

Comments