Front-end/타입스크립트로 블록체인 만들기

[TS] Interfaces

탱 'ㅅ' 2024. 1. 2. 16:53

interface의 두가지 용도 type vs. class

 

🏁 object type

specific value of concrete type

오직 객체의 모양을 특정해주기 위함

 

type과 interface는 오브젝트의 모양을 결정한다는 공통점이 있지만,

type은 다른 형태도 설명할 수 있는 반면 interface는 오직 객체만 가능하다.

그래서 type의 쓰임이 더 많다.

 

결론

 object → interface 

 그 외 (type alias, 특정값 등) → type 

이 방법이 더 객체지향 프로그래밍처럼 보여서 이해하기 쉽다

// interface로는 object 외 선언 불가
type Team = "red" | "blue" | "yellow"
type Health = 1 | 5 | 10

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

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

 

 

둘 다 목적은 같다.

둘 다 implemets를 사용해 상속할 수 있고, 추상클래스를 대체할 수 있다.

 

type은 새 property를 추가하기 위해 다시 선언될 수 없지만

interface는 항상 상속이 가능하다.

동일한 이름으로 여러 번 선언할 수 있고, TS는 자동으로 병합한다. ➤ 직관적

즉, 타입을 추가해야할 때 유용하며 type보다 확장성이 좋다.

  type interface
  concrete type - object  concrete type - object 
  concrete type - etc  
  type alias  
  specific value  
  추상 클래스 대체 (상속) 추상 클래스 대체 (상속) - 추천(객체지향/직관적)
  기존 type 상속하여 새로운 type 생성 (&) 기존 type 상속하여 새로운 type 생성 (extends)
  property 추가 위한 재선언 불가 property 추가 위한 재선언 가능
// 방법1. type
type User = { name: string }

type Player = User & { no: number }
🚫 type Player = {}

const tang: Player = {
	name: "tang"
	no: 17
}


// 방법2. interface
interface User { name: string }

interface Player extends User { no: number }
interface Player { health: number }
interface Player { major: string }

const tang: Player = {
	name: "tang",
	no: 1
	health: 100
	major: "football"
}


// 추상 클래스 대체
class Member implements User { // type도 interface도 상속 가능
	constructor(
		public name: string
	) {}
}

 

 

🏁 abstract class

인터페이스는 클래스는 아니지만 클래스와 닮아있고 클래스의 모양을 특정할 수 있게 해준다.

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

 

abstract class와 interface는 클래스의 모양을 알려준다는 공통점이 있지만,

컴파일시 JS 코드 결과에 abstract class는 일반 class로 존재하는 → 파일 크기가 좀 더 커지고, 추가 클래스가 만들어진다

반면 interface는 사라진다.

그래서 interface의 파일 사이즈가 더 작고 가볍다.  *권장

 

그러나

private property ❌

constructor() ❌

// 방법1. (abstract) class
abstarct class User {
     constructor() {
    	private firstName: string,
    	private 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()}`
    }
}


// 방법2. interface
interface User {
    firstName: string,
    lastName: string,
    sayHi(name: string): string,
    fullName(): string
}

interface Human {
    health: number
}

// 다중 인터페이스 상속 가능
class Player implements User, Human {
    constructor() {
    	// 인터페이스를 상속하면 private 불가
        private firstName: string,
        private lastName: string
    }
    fullName() {
	return `${this.firstName} ${this.lastName}`
    }
    sayHi(name: string) {
	return `Hello ${name}. My name is ${this.fullName()}`
    }
}


function makeUser(user: User): User { // interface는 type으로 사용 가능
    return {
        firstName: "tang",
        lastName: "lim",
        sayHi: (name) => "string",
        fullName: () => "xx"
    }
}
const makeUser = (user: User): User => ({
    firstName: "tang",
    lastName: "lim",
    sayHi: (name) => "string",
    fullName: () => "xx"
})

makeUser({
    firstName: "tang",
    lastName: "lim",
    sayHi: (name) => "string",
    fullName: () => "xx"
})

 

'Front-end > 타입스크립트로 블록체인 만들기' 카테고리의 다른 글

[TS] tsconfig.json  (0) 2024.01.04
[TS] Polymorphism + Generic Type + Interface  (1) 2024.01.04
[TS] Classes  (1) 2024.01.02
[TS] HW - Polymorphism, Generic Type  (1) 2023.12.21
[TS] Polymorphism 다형성  (0) 2023.12.20