단진
대체로 맑음
단진
  • 분류 전체보기 (162)
    • 개발 (112)
      • 회고 (25)
      • 개발과정 (28)
      • 개념 (14)
      • JavaScript (11)
      • TypeScript (12)
      • 알고리즘 (4)
      • GitHub (4)
      • 오류 (9)
      • TMI (5)
    • 일상 (15)
      • 사진 및 여행 (6)
      • 책 소개 (4)
      • 기타 TMI (5)
    • IT (16)
      • 개념 (5)
      • 데이터베이스 (6)
      • 딥러닝 (1)
      • TMI (4)
    • TMI (4)
      • 법률 TMI (4)
    • 보안 (15)
      • Dreamhack (5)
      • Root Me (10)
hELLO · Designed By 정상우.
단진

대체로 맑음

10. 타입스크립트(TypeScript) - Interface
개발/TypeScript

10. 타입스크립트(TypeScript) - Interface

2022. 9. 28. 22:18

Interface

  • 주로 다른 누군가가 데이터를 덮어쓰는 것을 방지하기 위해 private이나 protected property를 사용
  • 타입을 concrete 방법이 아니라 특정 값 중 하나만 갖도록 설정할 수도 있다
type Team = "red" | "blue" | "yellow"
type Health = 1 | 5 | 10

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

const a: Player = {
	nickname: "hello",
	team: "red",
	health: 10
}
  • Interface : 오브젝트의 모양을 설명하는 다른 방법
type Team = "red" | "blue" | "yellow"
type Health = 1 | 5 | 10

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

const a: Player = {
	nickname: "hello",
	team: "red",
	health: 10
}
  • TS에게 오브젝트의 모양을 알려주는 방법은 두가지가 있다
    • type 오브젝트 이름 = { 오브젝트 모양 }
    • interface 오브젝트 이름 { 오브젝트 모양 }
  • type 키워드는 interface 키워드에 비해 좀 더 활용할 수 있는게 많다
    • interface는 오로지 오브젝트의 모양을 타입스크립트에게 설명해 주기 위해서만 사용되는 키워드
interface Hello = string // 이런건 안됨. Hello는 오브젝트가 아니기 때문

💡 interface와 type은 둘 다 오브젝트의 타입을 설정할 수 있다.하지만, type이 좀 더 쓰임이 많다. 왜냐하면, interface는 오브젝트의 타입 “만” 지정할 수 있기 때문이다

 

 

인터페이스는 클래스와 닮았다

interface User {
	name: string
}
interface Player extends User {
}

const a : Player = {
	name: "hello"
}

// interface 사용
type User = {
	name: string
}
type Player = User & { // &연산자는 "and"를 의미
}

const a : Player = {
	name: "hello"
}

// type 사용

 

 

인터페이스는 property들을 축적시킬 수 있다

interface User {
	name: string
}
interface User {
	lastName: string
}
interface User {
	health: number
}

const a: User {
	name: "hello"
	lastName: "bye"
	health: 10
}
  • 같은 인터페이스에 다른 이름을 가진 property들을 쌓을 수 있다
    • type은 위와 같은 형태로 작성하면 오류가 발생한다

 

 

JS에서는 추상 클래스가 없다

  • TS에서 추상 클래스를 만들면 JS로 변환되는 과정에서 일반적인 클래스로 바뀌어버린다
    • JS에는 추상 클래스 라는 개념이 없기 때문이다
    • 그렇다면 왜 추상 클래스를 만드는가?
      • 다른 클래스들이 표준화된 모양, 표준화된 property와 메소드를 갖도록 해주는 청사진을 만들기 위해 추상 클래스를 사용한다
    • interface를 사용하면 가벼워진다
      • interface는 컴파일하면 JS로 바뀌지 않고 사라지게 된다

 

 

인터페이스를 쓸 때 클래스가 특정 형태를 따르도록 강제하는 법

  • 인터페이스는 constructor가 없다
    • 하지만, 인터페이스는 오브젝트나 클래스의 모양을 묘사하도록 해준다
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 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 사용
  • extends라는 말은 JS로 그대로 변환되므로 extends라는 말을 없애고 JS에 없는 단어로 바꾼다 → implements
    • implements를 쓰면 코드가 더 가벼워진다 → implemennts는 TS에만 존재하고 JS에는 존재하지 않기 때문이다
    • 단, interface를 상속할 때는 property를 private, protected로 만들지 못한다 → public이 되어야만 한다
    • 여러개의 interface를 상속 받기 위해서는 아래와 같이 작성한다
  • 또한, 클래스를 타입으로 쓸 수 있듯 interface도 타입으로 쓸 수 있다
interface User { ... }

function makeUser (user: User) { ... }

makeUser({
	firstName: "hello"
	lastName: "bye"
	fullName: () => "xx"
	sayHi(name) => "string"
})
  • 만약, interface를 return 한다면 class와 같이 new … 의 형태로 작성하지 않는다
    • interface의 내용만 작성하면 된다
interface User { ... }

function makeUser (user: User): User {
	return {
		firstName: "hello",
		lastName: "bye",
		fullName: () => "xx",
		sayHi(name) => "string"
	}
}

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

💡 interface를 argument로 넣어줄 때도 내용물만 넣으면 되고, interface를 return 할 때도 내용물만 넣으면 된다

 

 

Interface 정리

  • 인터페이스에는 원하는 메소드와 property를 클래스가 가지도록 강제할 수 있다
  • interface는 JS로 컴파일되지 않는다. 추상 클래스는 JS에서 일반적인 클래스로 바뀌어 컴파일 된다 → 파일 크기가 좀 더 커지고, 추가 클래스가 만들어진다는 뜻
  • class <class이름> implements <interface이름>

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

11. 타입스크립트(TypeScript) - Polymorphism + Generic + Class + interface  (0) 2022.10.01
9. 타입스크립트(TypeScript) - Class  (0) 2022.09.22
8. 타입스크립트(TypeScript) - Concrete Type & Generic Type  (0) 2022.09.04
7. 타입스크립트(TypeScript) - Overloading & Polymorphism (다형성)  (0) 2022.09.04
6. 타입스크립트(TypeScript) - 타입 & Call Signature  (0) 2022.09.04
    '개발/TypeScript' 카테고리의 다른 글
    • 11. 타입스크립트(TypeScript) - Polymorphism + Generic + Class + interface
    • 9. 타입스크립트(TypeScript) - Class
    • 8. 타입스크립트(TypeScript) - Concrete Type & Generic Type
    • 7. 타입스크립트(TypeScript) - Overloading & Polymorphism (다형성)
    단진
    단진

    티스토리툴바