[노마드 리액트 스터디] 14일차 - 타입스크립트(5)

lisoh·2023년 2월 20일
0
post-thumbnail

4.2 Interfaces (16:17)

type Friends = Array<string>

타입 Friends는 string의 배열이라는 뜻이야.

type Team = "read" | "blue" | "yellow"

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

이렇게 하면 team에 concrete 타입의 특정 값을 쓸 수도 있어.

타입스크립트에게 오브젝트의 모양을 알려주는 두 가지 방법

  • interface
  • type

둘의 다른 점은 type 키워드는 interface 키워드에 비해 좀 더 활용할 수 있는게 많다는고.
interface는 오로지 오브젝트의 모양을 타입스크립트에게 설명해 주기 위해서만 사용되는 키워드야.오로지 이 한 목적.
그에 반해 type 키워드는 오브젝트의 모양을 정해줄 수도 있고 특정 값들로만 제한해줄 수도 있고 타입 alias를 정해줄 수도 있오.

-> 오개념. interface는 오브젝트뿐 아니라 함수에 쓸 수도 있고, 증강을 할 수도 있다. 오로지 한 목적으로만 쓰이지 않음!!
타입은 그 자체로 alias임!

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

interface Player {
  nickname: string,
  team:Team
}

둘이 같은고. =만 다르다.

인터페이스는 클래스와 닮았어.

interface User {
  name: string
}

interface Player extends User {
}

const nico : Player = {
  name: "nico"
}

만약 네가 객체지향 프로그래밍에 관심이 있다면, 이건 더더욱 클래스처럼 보일거야.

위의 인터페이스는 아래의 타입으로 이렇게 표현할 수도 있어.

type User = {
  name:string
}
type Player = User & {
}

const nico : Player = {
  name:"nico"
}

인터페이스의 또 다른 특징은 property를 축적할 수 있는고야.
타입은 그럴 수 없오. 같은 인터페이스에ㅐ 다른 이름을 가진 Property를 쌓는 거 말야.

4.3 Interfaces part Two (16:27)

인터페이스랑 클래스를 합치는 방법.
추상화를 원할 때 클래스와 인터페이스를 사용할 때의 차이점

abstracct 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 'Hello ${name}, My name is ${this.fullName()}'
  }
}

추상 클래스는 새로운 인스턴스를 작성할 수 없어.

추상 클래스의 문제점은, 자바스크립트에는 abstract의 개념이 없다는거야.

한번 위의 추상 클래스를 인터페이스로 바꿔볼겡.

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 return `${this.firstName} ${this.lastName}`
  }
  sayHi(name:string){
    return 'Hello ${name}, My name is ${this.fullName()}'
  }
}

implements를 쓰면, 가장 먼저 코드가 더 가벼워져.
자바스크립트로 변환된 모습에서는 인터페이스가 안보이거든.
근데 인터페이스를 상속하는 클래스는 private이나 Protected를 쓸 수 없어.

4.4 Recap (10:16)

profile
프론트엔드 개발자를 꿈꾸는 개발초보 호랑이

0개의 댓글