타입 스크립트 - 인터페이스

Seong·2022년 11월 10일
0

Type_Script

목록 보기
5/7

인터페이스:클래스, 오브젝트의 모양을 특정해준다.

  • 인터페이스는 상속을 받을수 있음.
type Team = 'red' | 'blue' | 'yellow'
type Heaalth = 1 | 5 | 10

interface Human {
  name:string
}

interface Person extends Human { //상속
  nickname: string,
  team: Team,
  health: Heaalth
}

const test: Person = {
  name:'seong',
  nickname: "netban",
  team: "yellow",
  health: 10
}
  • 인터페이스는 프로퍼티들을 중복시킬수있음
interface Human {
  name:string
}

interface Human {
  age:number,  
}
interface Human {  //Human이 하나로 합쳐짐
  first_name : string
}

interface Person extends Human {
  nickname: string,
}

const test: Person = {
  name:'seong',
  age: 25,
  first_name:'SeungYoung',
  nickname: "netban",
}

클래스에서 인터페이스 사용하기

  • 인터페이스는 컴파일하면 JS로 바뀌지않고 사라진다.
  • 인터페이스를 상속받을때는 JAVA와 같이 implements를 사용한다 (이건 Type도 동일)
  • 인터페이스를 상속할때에는 프롬퍼티를 private로 상속받지 못함
interface Name {
  firstName: string,
  lastName: string,
  sayHi(name: string): string;
  fullName(): string
}

class Myname implements Name {
  constructor(
    public readonly firstName: string,
    public readonly lastName: string
  ) { }
  sayHi(name: string): string {
    return `hi ${name}, I'm ${this.fullName()}`
  }
  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }

}
  • 타입스크립트 커뮤니티에서는 클래스나 오브젝트의 모습을 특정할 때에는 interfacce, 그 외에는 type을 사용하는경우가 많음
profile
메모장

0개의 댓글