본문 바로가기
프로그래밍/Typescript

#4-2 Interfaces

by 퐁당당당 2025. 1. 20.

4.2 Interfaces -1

(1) readonly

지금가지 우린 public, private, protected 세 가지 종류를 배웠다.

조금 다른 맥락에서 존재하는 readonly라는 키워드에 대해 알아보자. readonly는 앞의 세 가지 중 public이랑 제일 유사한 것 같다. 이 종류들을 볼 때 우리가 확인해야 할 것은

  1. 외부에서 접근이 가능한가?
  2. 외부에서 수정이 가능한가?

이 두 가지다.

readonly는 public과 같이 외부에서 접근이 가능하지만, 수정은 불가능하다.

class Word{
    constructor(
        public readonly term :string,
        public readonly def :string
    ){}
}
  1. readonly : public뒤에다가 적어준다

readonly는 외부에서 접근이 가능하다는 특징이 있기 때문에, 외부 접근이 불가능한 protected와 private에 사용하는 것은 의미가 없다.

(2) Concrete types

지금까지 type을 명시할 때는 변수가 가질 수 있는 자료형만 적었다. 하지만 구체적으로 어떤 값들을 가질 수 있는 지를 정할 수도 있다

type Team = "red"|"blue"|"green"

type Player ={
    age : number,
    team : Team
}
  1. number : age라는 변수가 가질 수 있는 값은 number형임
  2. team : Team : team 이라는 변수가 가질 수 있는 값은 위에 명시해둔 것 처럼 red, blue, green 중 하나임

(3) Interfaces

interface는 객체의 type만 지정할 수 있는 키워드이다. 사실 type을 써서 구현할 수도 있지만, interface로는 ‘객체의 type’만을 지정할 수 있다.

(사실 type이랑 조금 다르다. 이 부분은 차차 알아가도록 하자. 아무튼 기능은 동일하다는 것)

type Team={
    nickname: string,
    team: Team,
    health: Health    
}

interface Team{
    nickname: string,
    team: Team,
    health: Health    
}

위에 type을 이용하여 객체를 구현한 것과, interface를 사용하여 표현해준 코드. 둘 모두 같은 의미를 가진다.

(4) Interface를 이용한 상속

상속

Interface를 활용하여 상속을 할 수 있다. abstract class를 extend할 때의 기능과, 문법이 매우 유사하다.

interface Player = {
    name : stiring
}

const User extends Player ={
}
  1. User : Player 인터페이스를 확장해서 사용할 놈
  2. extends Player : 확장할 인터페이스

abstract class와 다른 점은, 따로 abstract 같은 키워드를 입력할 필요가 없다는 것이다.

(5) Interface를 이용한 자동 병합

Interface라는 키워드를 사용해서 여러 개의 필드를 적어주면 자동으로 합쳐진다.

interface User ={
    name : string
}

interface User ={
    age : number
}

이렇게 두 번 작성하면 user라는 class에 자동으로 name, age에 대한 type이 명시되어 있는 것과 같은 역할을 한다.

4.3 Interfaces -2

지금부터는 classinterface가 어떻게 합쳐지는지 확인해보려고 한다. interface는 객체를 위한 문법인데 class랑 합쳐진다고 하면 뭔가 이상하게 느껴질 수도 있다.

(1) Interface vs abstract class - Complie

  • 바로 class로 쓰는 것이 불가능함 ↔ interface는 가능
  • Js로 컴파일 될 때 결국 class로 남음
  • 바로 선언해서 사용할 수 있음
  • Js로 컴파일하면 사라짐

abstract class처럼 코드를 쓰면 코드가 무거워진다. (컴파일 할 때 Js에 남으니까)

(2) Interface vs abstract class - Private

  • 기본적으로 모든 멤버가 public이기 때문에 상속받았은 객체도 private를 사용할 수 없다
  • 상속받은 class가 private를 사용할 수 있다.

어디에도 끼지 못한 Interface 의 추가적인 특징을 적어보면

  • constructor함수를 사용하지 않아도 된다는 점
  • 이 자체로 type으로 사용할 수 있다는 점

에서 형식이 자유롭고 활용 가능성이 높다는 것을 알 수 있다.

(3) 상속받는 Class 만들기

  • Using abstract classabstract class → extends → new class
  • abstract class User{ constructor( protected firstname: stirng, protected lastname: string ){} abstract fullname():stirng } class Player extends User{ fullname(){ return `${this.firstname} ${this.lastname}` } }
  • Using Interfaceinterface → implements → new class!
  • interface User{ fistname: 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}` } }

interface를 활용하면 여러 개의 interface를 받을 수도 있다.

interface User{
...
}

interface Health{
    public health: number

class Player implements User,Health{
...

'프로그래밍 > Typescript' 카테고리의 다른 글

TypeError: prevState.boardId is not iterable  (0) 2025.03.20
#4-1 Classes and Interfaces - Class  (2) 2025.01.20
#3. Functions  (0) 2025.01.14
#2. Overview of the Typescript  (1) 2025.01.14
Intro  (0) 2025.01.14