[Typescript] type과 interface, 그리고 abstract class

joy·2024년 12월 23일
post-thumbnail

▪️type VS interface


type 사용법과 특징

1. 객체의 모양 정의

type은 객체의 구조를 정의할 때 사용할 수 있다.

type Player = { 
    nickname: string,
    healthBar: number
}

const nico: Player = {
    nickname: "nico",
    healthBar: 100
}

2. 타입 별칭 (Type Alias)

type은 새로운 타입 별칭을 만드는 데 사용된다. 예를 들어, 특정 값의 타입을 간결하게 표현할 수 있다.

type Food = string;
const bulgogi: Food = "delicious korean food";

별칭은 다른 타입 정의에서도 재사용이 가능하다.

type Nickname = string;
type Health = number;

type Player = {
    nickname: Nickname,
    healthBar: Health
};

3. 제한된 값만 허용하는 타입

type은 특정 값들로 제한된 타입을 정의하는 데 유용하다.

type Team = "red" | "blue" | "yellow";
type Health = 1 | 5 | 10;

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

이 경우, Player의 team은 반드시 "red", "blue", "yellow" 중 하나만 가질 수 있다.
health도 마찬가지로 1, 5, 10 중 하나로 제한된다


interface 사용법과 특징

1. 객체의 모양 정의

interface는 객체의 구조를 정의하기 위해 사용된다.

interface Player {
    nickname: string,
    team: "red" | "blue" | "yellow",
    health: 1 | 5 | 10
}

type과 비슷하게, 객체의 구조를 정의하는 데 유용하다.

2. 상속 (Extends)

interface는 상속을 통해 다른 인터페이스를 확장할 수 있다.

interface User {
    name: string
}

interface Player extends User {
    team: string
}

const nico: Player = {
    name: "nico",
    team: "red"
};

💡 type에서도 비슷한 결과를 & 연산자를 사용하여 구현할 수 있다.

type User = {
    name: string
}

type Player = User & {
    team: string
};

const nico: Player = {
    name: "nico",
    team: "red"
};

3. 인터페이스의 축적

interface는 같은 이름으로 여러 번 정의할 경우, 속성이 병합된다. 이는 type과는 다른 interface의 특징이다.

interface User {
    name: string;
}

interface User {
    age: number;
}

const nico: User = {
    name: "nico",
    age: 25
};

type, interface 둘 다 객체의 모양 정의하는데 사용하고
클래스 구현을 강제할 수 있으며 abstract class를 대체할 수 있다.

type으로 abstract class 대체

type PlayerA = {
    name: string
}

type PlayerAA = PlayerA & {
    health: number
}

class User implements PlayerAA {
    constructor(
        public name: string,
        public health: number
    ){}
}

interface로 abstract class 대체

interface PlayerB {
    name: string
}

interface PlayerBB extends PlayerB {
    health: number
}

class User implements PlayerBB {
    constructor(
        public name: string,
        public health: number
    ){}
}

그럼 언제 무엇을 사용할까?

클래스나 객체의 모양을 정의하고 싶으면 interface를 사용하고 그 외의 다른 모든 경우에서는 type을 사용한다고 한다.


▪️abstract class VS interface

추상클래스 (abstract class)

  • 인스턴스를 생성할 수 없다.
    추상 클래스는 새로운 객체를 직접 생성하지 않고, 다른 클래스가 상속받아 동작 방식을 정의해야 한다.

  • 자바스크립트로 컴파일되면 일반적인 클래스 형태로 변환된다.

abstract 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()}`;
    }
}

인터페이스 (interface)

  • 자바스크립트로 컴파일되지 않고, 타입스크립트 내에서만 존재하므로 코드가 더 가벼워진다.

  • 클래스가 특정 구조를 따르도록 강제하는 데 사용된다.

  • 인터페이스를 구현할때는 property를 private 으로 만들지 못한다.

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 `${this.firstName} ${this.lastName}`;
    }

    sayHi(name: string) {
        return `Hello ${name}. My name is ${this.fullName()}`;
    }
}

그럼 언제 무엇을 사용할까?

interface는 코드가 더 가볍고 간단하고 객체의 구조(Shape)만 정의할 때 사용한다.
예를 들어, 여러 클래스가 동일한 구조를 공유해야 하지만 구체적인 구현은 다를 때 적합하다.

반면, abstract class는 기본 구현을 제공할 수 있고, 구체적인 기능과 추상적인 기능을 혼합할 수 있으므로 공통적인 구현(기본 메서드 또는 속성)이 필요한 경우 사용하기에 적합하다.

profile
대충대충 꾸준히 🐢

0개의 댓글