타입스크립트 part.3

박경준·2022년 6월 23일
0

TypeScript

목록 보기
3/3

객체지향 언어에서의 TS

  • 기본 클래스
class Player {
  constructor(
  	private firstName:string,
    private lastName:string,
    public nickname:string
  ) {}
}

const nico = new Player("nico", "las", "니꼬");

nico.firstName // error - private
nico.nickname // works
  • 추상 클래스
// 추상 클래스는 직접 인스턴스를 못만들지만,
abstract class User {
  constructor(
    // private은 클래스 외부, 자식 클래스에서도 접근할 수 없지만,
    // protected는 자식 클래스에서는 접근할 수 있다.
  	protected firstName:string,
    protected lastName:string,
    protected nickname:string
  ) {}
  // 추상 메서드 - call signature만 갖고 있음
  abstract getNickname():void
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

// 다른 클래스에 상속시킬수 있다.
class Player extends User {
  getNickname() {
    // 추상메서드의 구현부
    console.log(this.nickname)
  }
}

const nico = new Player("nico", "las", "니꼬");
nico.getFullName()

interface

// type 명시에는 타입 종류 뿐만 아니라 값을 직접 넣을수도 있다.
type Team = "red" | "blue" | "yellow"

// interface는 object의 모양을 알려주기 위함.
interface Player {
  nickname:string,
  team:Team
}
/*
이것과 같음.
type Player = {
  nickname:string,
  team:Team
}
*/

const nico : Player = {
  nickname: "nico",
  team: "red"
}
  • interface 다른 예시
interface User {
  name:string
}

// 상속도 가능
interface Player extends User {
  health:number
}
const nico : Player = {
  name: "nico",
  health: 10
}

interface로 class 만들기

// 추상 클래스처럼 클래스의 모양을 보여주지만, JS로 컴파일되지 않아 파일 크기를 줄일수 있다.
// 다만 constructor를 자식 클래스에서 반복적으로 선언해줘야한다.
interface User {
  firstName:string,
  lastName:string,
  sayHi(name:string):string,
  fullName():string,
}
interface Human {
  health:number
}

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

interface를 type으로 쓰기

interface User {
  firstName:string,
  lastName:string,
  sayHi(name:string):string,
  fullName():string,
}

function makeUser(user: User): User {
  return {
    firstName: "nico",
    lastName: "las",
    fullName: () => "nicolas",
    sayHi: (name) => "string"
  }
}

// interface를 type으로 쓸때는 class처럼 new로 인스턴스를 만들지 않아도 되고,
// 그냥 interface에서 정의된 object를 넣으면 된다.
makeUser({
    firstName: "nico",
    lastName: "las",
    fullName: () => "nicolas",
    sayHi: (name) => "string"
})
profile
빠굥

0개의 댓글