본문 바로가기

개발/JavaScript

[TS] Interfaces

 

Interface

- 타입에 비해 제한적 -> object의 형태만 정할 수 있다.

- 객체지향적으로 활용도가 높다.

- JS로 컴파일 시 사라짐

- 클래스와 object의 모양을 정의할 때 사용, 그 외에는 type 사용

 

 

type:

type Team = "red" | "blue" | "yellow"; // 특정 값으로 제한
type Health = 1 | 5 | 10;

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

const jaja : Player = {
    nickname:"jaja",
    team:"blue",
    health:10
};

interface:

interface Player { // object의 모양 결정
    nickname: string,
    team: Team,
    health: Health
};

- 같은 인터페이스에 속성을 추가할 수 있다.

// interface
interface User {
    name:string
}

interface User {
    lastName: string
}

interface User {
    health:number
}

const jaja : User = {
    name: "jaja",
    lastName: "ho",
    health:10
}

 

 

type과 interface 비교

type PlayerA = {
    name:string
}
type PlayerAA = PlayerA & { // type 상속 개념
    lastName:string
} // property 추가 시 새로운 타입을 생성해야 함

const playerA:PlayerAA = {
    name:"nene",
    lastName:"ko"
}

//////
interface PlayerB {
    name:string
}
interface PlayerBB extends PlayerB {
    lastName:string
}
interface PlayerBB { // PlayerBB interface에 property 추가
    health: number
}

const playerB : PlayerBB = {
    name: "nana",
    lastName: "ko",
    health: 10
}

 

- 클래스는 타입과 인터페이스 모두 상속할 수 있다.

type PlayerA = {
    firstName:string
}
interface PlayerB {
    firstName:string
}

interface Player extends PlayerB {
    lastName:string
}

class User implements PlayerA {
    constructor(
        public firstName:string
    ) {}
}

class UserB implements Player {
    constructor(
        public firstName:string,
        public lastName:string
    ){}
}

 

 

추상클래스와 비교

- 추상클래스: 표준화된 property와 메서드를 갖도록 해주는 청사진을 만들기 위해 사용

  -> 자바스크립트로 변환 시 일반 클래스로 변환

abstract class User { // 추상 클래스: 클래스의 청사진-설계도 제시
    constructor (
        protected firstName:string,
        protected lastName:string
    ) {}

    abstract sayHi(name:string):string
    abstract fullName():string
}

class Player extends User { // sayHi(), fullName() 반드시 구현 필요
    fullName() {
        return `${this.firstName} ${this.lastName}`
    }
    sayHi(name:string) {
        return `Hello ${name}. My name is ${this.fullName()}`
    }
}

- 인터페이스: 클래스나 객체의 모양을 지정, 자바스크립트 코드로 변환되지 않음 -> 소스 크기를 줄여준다.

interface User {
    firstName:string,
    lastName:string
    sayHi(name:string):string
    fullName():string
}
interface Human {
    health:number
}
class Player implements User, Human { // interface의 property를 반드시 가져야함
    constructor( // 접근제어자 설정 불가, 생성자를 작성해야하는 번거로움 발생
        public firstName:string,
        public lastName:string,
        public health:number
    ) {}
    fullName() {
        return `${this.firstName} ${this.lastName}`
    }
    sayHi(name:string) {
        return `Hello ${name}. My name is ${this.fullName()}`
    }
}

function makeUser(user: User): User { // interface를 타입으로 사용할 수 있음 => 인스턴트 생성 불필요
    return {firstName: "ho",
        lastName: "ho",
        sayHi: (name:string) => "hi",
        fullName: () => "hoho"
    } // interface 형식을 따른 object로 return 가능
}

 

'개발 > JavaScript' 카테고리의 다른 글

[TS] declaration file, JSDoc  (0) 2022.08.07
[TS] 타입스크립트 프로젝트 설정  (0) 2022.08.05
[TypeScript] Classes  (0) 2022.08.04
[TypeScript] Functions  (0) 2022.08.04
[TypeScript] Types  (0) 2022.08.04