본문 바로가기

TypeScript

interfaces 타입스크립트 인터페이스란? var.2

interface User {
    name:string
}

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

const harim : User = {
    name:"하림",
    lastName:"최",
    health:100
}

여러개의 같은 이름의 인터페이스를 하나로 묶어준다 

인터페이스는 조금더 나은 합체능력을 가진다. (같은이름의 프로퍼티를 쌓을수있다.)

 

추상클래스로 보는 인터페이스의 차이점

사용전

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}. 내이름은 ${this.fullName}`
    }
}

사용후 (implements)

인터페이스는 자바스크립트로 빌드되면 사라지기때문에 가볍다.

interface User {
    firstName: string,
    lastName: string,
    sayHi(name: string): string
    fullName(): string
}
interface Human {
    health: number
}
class Player implements User, Human {
    constructor(
        public firstName: string,
        public lastName: string,
        public health: number
    ) { }
    fullName() {
        return `${this.firstName} ${this.lastName}`
    }
    sayHi(name: string) {
        return `hello ${name}. 내이름은 ${this.fullName()}`
    }
}

const makeUser = (user: User):User => {
    return {
        firstName: "최",
        lastName: "하림",
        fullName: () => "최하림",
        sayHi: (name) => "안녕"
    }
}


//makeUser({
 //       firstName: "최",
   //     lastName: "하림",
     //   fullName: () => "최하림",
       // sayHi: (name) => "안녕"
// })

makeUser 부분에 리액트를 적용하면 쉽게 결과를 출력할수있다는 생각이든다.