home
자바
home
🔥

#4.2 ~ #4.4

#4.2 Interfaces
#4.3 Interfaces part Two
클래스 필드에 readonly를 붙이면 수정할 수 없다.

타입이 특정 값을 가지도록 제한할 수 있다.

type Team = "read" | "blue" | "yellow" //Team 타입을 가진 프로퍼티는 read or blue or yellow만 올 수 있다. type Health = 1 | 5 | 10 //Health 타입을 가진 프로퍼티는 1 or 5 or 10만 올 수 있다. type Player = { nickname: string, team: Team, health: Health }
TypeScript
복사

Interface

인터페이스는 오로지 오브젝트의 모양을 타입스크립트에게 설명해 주기 위해서만 사용되는 키워드 이다.
type Player = { nickname: string, team: string, health: string } // 위의 타입 선언 방식과 같다. interface Player { nickname: string, team: string, health: string }
TypeScript
복사

Interface 상속

//interface interface User { name: string } //interface 상속 interface Player extends User { } // type type User = { name: string } // & 연산자로 해당 타입을 상속받은 것처럼 사용할 수 있다. type Player = User & { } const jjw: Player = { name: 'jungJaeWoong' }
TypeScript
복사
오브젝트의 모양을 알려줄 때는 type보다 interface를 사용하는 것이 더 좋겠다. (더 객체지향 프로그래밍처럼 보여서 이해하기 쉽다)
interface
interface User { name: string } interface User { lastName: string } interface User { health: number } //다른 이름을 가진 프로퍼티를 쌓을 수 있다. const jjw: User = { name: 'jjw', lastName: 'woong', health: 100 }
TypeScript
복사
type
type User = { name: string } //error //같은 User 타입이 있어서 오류 type User = { lastName: string } type User = { health: number }
TypeScript
복사

추상클래스는 인터페이스로 바꿔 구현할 수 있다

추상클래스
abstract class User { constructor( protected fisrtName: string, protected lastName: string ) {} abstract sayHi(name: string): string abstract fullName(): string }
TypeScript
복사
인터페이스
interface User { firstName: string, lastName: string, sayHi(name: string): string fullName(): string } interface Human { health: number } class Player implements User, Human { //User, Human 인터페이스가 가진 프로퍼티들이 구현되지 않으면 오류가 난다. constructor( public firstName: string, public lastName: string ){} sayHi(name: string) { return `${this.firstName} ${this.lastName}` } fullName() { return `${this.firstName} ${this.lastName}` } }
TypeScript
복사
implements 키워드는 자바스크립트에 없는 키워드이기 때문에 자바스크립트로 변환 시 코드가 가벼워진다. (interface도 마찬가지)
인터페이스 상속 시 프로퍼티를 private으로 만들지 못한다. (단점)
여러개의 인터페이스를 상속받을 수 있다.
인터페이스로 클래스 타입 정의 시 constructor를 쓰지 않아도 된다.