[TS 공부 with 노마드 코더] #4.2 Interfaces

SOLEE_DEV·2022년 7월 10일
0

Typescript

목록 보기
8/10
    static hello() {
        return "hello";
        // 객체 생성할 필요없이 클래스에서 접근하면 생성 가능~
    }
    
    ...
    
    class Word {
      constructor(
          public readonly term: string,
          public readonly def : string,
          // 모두에게 보여주고는 싶지만, 수정은 불가능하게!
      ){}
    }

    const kimchi = new Word("kimchi", "한국의 음식")
    // kimchi.def = "한국 김치" readonly라 직접 수정 안됨
    console.log(kimchi.def);
// concrete type = 타입 alias를 위해서 쓰거나 특정 타입만 허용하게!
type Team = "red" | "blue" | "yellow "
type Health = 1 | 5 | 10


type Player = {
    // type을 쓰게 되면 활용할 수 있는게 더 많아지긴 함~
    nickname: string,
    team: Team,
    health: Health,
}

interface Person {
    // 인터페이스의 역할 : Object의 모양을 묘사하는데 쓸 수 있음

    // 차이점 : ex) interface Hello = string -> 못씀
    // 인터페이스는 오로지 오브젝트의 모양을 ts에게 설명해주기 위해서만 사용되는 키워드

    // 인터페이스를 다루는게 클래스를 다루는 듯한 느낌이라 더 쉬움
    nickname: string,
    team: Team,
    health: Health,
}

const player1: Player = {
    nickname: "sol",
    team: "red",
    health: 1
}
interface User {
    name: string
}

interface Player extends User {
    // 하지만 인터페이스를 쓰면 좀 더 객체지향 프로그래밍처럼 표현 o
    
}

// type Player = User & { // 헉;;; super cool~~~;;;
//     // type은 종류에 관계 없이 어떠한 타입을 만들 때 다 쓸 수 있음

// }

const nick: Player = {
    name: "nico"
}
// type User = {
//     name: string
// }

// type User = {
//     lastName: string
// } => 중복된다고 막음!

interface User {
    name: string
}

interface User {
    lastName: string
}

interface User {
    health: number
}

const nico: User = {
    // 인터페이스를 각각 만들어도 ts가 알아서 하나로 합쳐줌!
    name: "",
    lastName: "",
    health: 0
}
profile
Front-End Developer

0개의 댓글