type Team = "red" | "blue" | "yellow"
type Health = 1 | 5 | 10
// type
type Player = {
nickname: string,
team: Team,
health: Health
}
// interface
interface Player {
nickname: string,
team: Team,
health: Health
}
상속 시, property 추가 시 차이점
// type
type PlayerA = {
name:string
}
type PlayerAA = PlayerA & {
lastName:string
}
const playerA: PlayerAA = {
name:"kyoorim",
lastName:"lee"
}
// interface
interface PlayerB {
name:string
}
interface PlayerB {
lastName: string
}
interface PlayerB {
health: number
}
const playerB: PlayerB = {
name:"kyoorim",
lastName:"lee",
health: 10
}
interface Hello = string // 이렇게 쓰는것 불가 !!! type은 가능!
interface User {
readonly name: string
}
interface Player extends User {
}
const nico: Player = {
name: "nico"
}
type으로는 이렇게 못함
interface User {
name: string
}
interface User {
lastName: string
}
interface User {
health: number
}
const kyoorim: User = {
name: "kyoorim",
lastName: "Lee",
health: 10
}
interface
를 썼을 때 코드 크기가 줄어들고 파일 크기가 가벼워짐=> typescript에만 존재하고 js에는 없는 개념임!
class를 썼을 때
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()}`
}
}
instance를 썼을 때
interface
는 가볍다. 컴파일하면 js로 바뀌지 않고 사라짐interface
를 상속 시property
를 private
으로 만들지 못함interface
를 상속할 수 있음interface User {
firstName: string,
lastName: string,
sayHi(name:string): string,
fullName(): string
}
interface Human {
health: number
}
class Player implements User, Human { // implements => Player가 User 인터페이스를 상속해야한다고 알려주고 있음
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()}`
}
}