[TS] Interface

404·2022년 6월 20일
0

JS ❤️ TS

목록 보기
5/6
post-thumbnail

TS로 배우는 OOP (2)

More strict type

지금까지 타입을 선얼할 때 concrete type 선언을 통해 아래와 같이 작성하는 법만 공부했다.

type Team = string;

type Player = {
  nickname: string,
  team: Team
};

const funco:Player = {
  nickname : "funco",
  team : "red"
};

좀 더 강한 제약을 주기 위해 아래와 같이 team 명에 들어올 수 있는 값들을 특정할 수 있다.

type Team = "red" | "blue" | "white";

type Player = {
  nickname: string,
  team: Team
};

const funco:Player = {
  nickname : "funco",
  team : "red" // "red" or "blue" or "white" only available
};

Interface

  • Interface는 객체의 모양을 결정해주는 용도로만 사용할 수 있다. 아래 예시는 위와 같은 코드이다.
  • Interface는 type처럼 type color = string 과 같은 타입지정엔 쓸 수 없다.
  • Interface는 컴파일시 평범한 JS로 남지 않고 사라진다.
type Team = "red" | "blue" | "white";

interface Player {
  nickname: string,
  team: Team
};

const funco:Player = {
  nickname : "funco",
  team : "red"
};
  • Interface는 class와 같은 형태로 상속 (확장)이 가능하다.
interface Player {
  nickname: string,
  team: string
};

interface User extends Player {

}

const funco:User = {
  nickname : "funco",
  team : "red"
};
  • Type을 사용해도 상속(확장)은 가능하지만 class 문법에 익숙한 사람이라면 Interface를 선호할것 같다.
type Player = {
  nickname: string,
  team: string
};
type User = Player & {

} // & 을 사용한 type의 상속

const funco:User = {
  nickname : "funco",
  team : "red"
};
  • Interface는 property를 축적할수있다. (자동병합)
interface Player {
  nickname : string
}

interface Player {
  team : string
}

interface Player {
  age : number
}

const funco:Player = {
  nickname : "funco",
  team : "red",
  age : 32 // if funco don't have 'age' property => error
};

Abstract class & Interface

  • 추상 클래스의 user와 이를 상속받은 Player 클래스를 만들었다.
abstract class User {
  constructor (
    protected firstName : string,
    protected lastName : string
  ){}
  abstract sayHi(name:string) : string
  abstract fullName():string
}

class Player extends User{
  fullName(){
    return `${this.firstName} ${this.lastName}`
  }
  sayHi(name:string){
    return `Hi ${name}? my name is ${this.fullName()}`
  }
}

위 코드는 아래의 JS 코드로 변환된다.

  • 이번엔 Interface를 상속받은 Player 클래스를 만들었다.
interface User {
  firstName : string,
  lastName : string
  sayHi(name:string) : string
  fullName():string
}

class Player implements User{
  constructor(
    public firstName:string,
    public lastName:string
  ){}
  fullName(){
    return `${this.firstName} ${this.lastName}`
  }
  sayHi(name:string){
    return `Hi ${name}? my name is ${this.fullName()}`
  }
}

위 코드는 아래의 JS 코드로 변환된다.

  • 베이스 클래스 (인터페이스)의 영향을 받는건 동일하지만 Interface를 상속받는 경우 베이스 interface가 변환된 코드에 남지 않는다. 따라서 코드가 좀 더 가벼워지는 효과가 있다. 하지만 interface를 상속받는 경우 private 프로퍼티는 사용할 수 없다.
profile
T.T

0개의 댓글