본문 바로가기
Front-end/Typescript

[TypeScript] Interface

by JiGyeong 2022. 8. 1.

 

 

  • tyep, interface 둘다 타입스크립트에게 오브젝트의 모양을 설명해 주기 위해 존재한다.

TypeScript 사용 방법 1 (type alias)

type Food = string;
const kimchi:Food = "delicious"

TypeScript 사용 방법 2 (concrete type)

type Player = {
    ninckname: string,
    healthBar: number
}
const nico: Player = {
    ninckname: "jigyeong",
    healthBar: 1
}

TypeScript 사용 방법 3 (concrete value)

type Team = "red" | "blue" | "yellow"
type Player2 = {
    team:Team,
    ninckname?: string,
    healthBar?: 1|5|10
}
const player2: Player2 = {
    team: "red"
}

TypeScript 사용 방법 4 (Interface)

interface Player3 = string 은 불가 interface는 오직 Object의 type을 정의해줄 때 사용

interface Player3 {
    team:Team,
    ninckname?: string,
    healthBar?: 1|5|10
}
const player3:Player3 = {
    team:"yellow"
}

TypeScript 사용 방법 5 (Extends Interface)

interface User {
    name: string
}
interface Player4 extends User {
    
}
const user:Player4 = {
    name: "dd"
}

extends 구문은 아래와 같이 바꿔 사용할 수 있다.

// interface 사용
interface Player4 extends User {
    
}

// type 으로 선언할 경우 아래와 같이 사용
type Player4 = User & {
    
}

Interface 응용

[abstract]

  • 다른 Class 가 따라야 할 규칙 설계. new User 는 못씀. extends 만 가능.
  • Javascript로 컴파일 될 땐 class 로 만들어짐.
abstract class User {
    constructor(
        protected firstName: string,
        protected lastName: string
    ){}

    abstract sayHi(name:string):string
    abstract fullname():string
}

class Player extends User{
    sayHi(name: string): string {
        return `${name} Hi`
    }
    fullname(): string {
        return `${this.firstName}` // firstName 이 private 일 경우 여기(구현체)에서 호출 못함.
    }

}

[interface]

  • [abstract] 에 반해 [interface] 는 컴파일하면 Javascript에서는 사라짐.
  • implements 키워드를 사용. Javascript에서는 사라짐.
  • 이런점에서 Interface가 더 가볍다고 할 수 있음.

문제점

  • interface 상속할 땐 private, protected 으로 만들지 못함
interface User2 {
    firstName: string,
    lastName: string,
    sayHi(name:string):string,
    fullname():string
}

class Player2 implements User2 { 
    constructor(
        public firstName:string,
        public lastName:string){}

    sayHi(name: string): string {
        return `${name} Hi`
    }
    fullname(): string {
        return `${this.firstName}` // firstName 이 private 일 경우 여기(구현체)에서 호출 못함.
    }

}

interface 여러개 상속하고 싶을때 ,(comma) 이어 붙여서 사용할 수 있다.

interface Human {
    health: number
}
class Player3 implements User2, Human {
    constructor(
        public firstName:string,
        public lastName:string,
        public health:number){}
}

interface도 type으로 사용 가능

function makeUser2(user:User2){
    return "hi"
}
makeUser2({
    firstName: "aa"
    , lastName: "bb"
    , fullname: () => "xx"
    , sayHi: (name) => `${name}`
})

Generics

new Localstorage<string>() 부분에서 <string>이 generic으로 넘기는 타입을 의미한다.

TypeScript가 <T>를 string으로 바꿔준다.

 

 

Conclusion

  • tyep, interface 둘다 타입스크립트에게 오브젝트의 모양을 설명해 주기 위해 존재한다.
  • type을 상속하려면 또다른 type을 만들어 상속한다.
  • interface는 같은 명칭을 계속 선언하여 축적이 가능하다.
interface PlayerB {
    name:string
}
interface PlayerB {
    lastName:string
}
const playerB:PlayerB = {
    name: "",
    lastName: ""
}
  • type, interface 둘다 implenets 해서 사용이 가능하다.
  • type, interface 둘다 추상클래스를 대체하여 사용할 수 있다.

 

  • interface : 클래스나 오브젝트의 모양 정의할 때 사용 (상속할때 보다 직관적임)
  • type : 타입 alias 나, 특정 값으로 타입을 제한할 때 사용

 

'Front-end > Typescript' 카테고리의 다른 글

[TypeScript] Class  (0) 2022.08.01
[TypeScript] Generics  (0) 2022.07.25
[TypeScript] Basic Overview  (0) 2022.07.21