본문 바로가기
front-end/TypeScript

[TS]07 type과 interface

by -제이리 2022. 5. 16.
728x90
320x100

type

- 타입스크립트에게 오브젝트의 모양을 설명해 줄 수 있다.
- 여러방면으로 쓰일 수 있다. (오브젝트의 모양을 알려주는데 쓸 수도 있고 타입이 string이라고 알려줄 수도 있다. 또 타입 alias(대체명)를 쓸 수 있다. 등등 여러종류의 타입을 설명할 수 있다.)
 
// 예시1: Alias를 알려줌
type Nickname = string
type Health = number

// 예시2: 오브젝트의 모양을 알려줌 
type Player = {
  nickname:Nickname,
  helthBar:Health
}

const tom:Player = {
  nickname:'tom',
  helthBar:10
}

// 예시3: 타입이 string이라는것을 알려줌
type Food = string;

const banana:Food = '바나나'

// 예시4: 배열을 나타내도록 할 수도 있음
type Friends = Array<string>

// 예시5: 타입을 지정된 옵션으로만 제한 할 수 있다.
type Team = 'red' | 'blue' | 'yellow'
type Health = 1 | 5 | 10

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

const jack : Player = {
  nickname:'Jack',
  team:'red',
  health:1
}

 

interface

오직 오브젝트의 모양을 타입스크립트에게 설명해주기 위해서만 사용된다.(interface Hello = string 이런거 작동 못함 )
 
type: 다양한 목적으로 사용될 수 있음
interface: Only object
// type과 interface 모두 오브젝트의 모양을 결정한다는 공통점이 있다.

// 이렇게 쓰나
type Player = {
  nickname:Nickname,
  helthBar:Health
}
// 이렇게 쓰나 기능은 같음
interface Player {
  nickname:Nickname,
  helthBar:Health
}

//--------------------------------------------
// interface 와 type의 차이점 (문법적)
// - interface: 문법 구조가 객체지향 프로그래밍과 매우 유사하다
interface User {
  name:string
}

interface Player extends User {
}
const tom: Player = {
  name:'Tom' 
}

// - type
type User = { // '='이 추가된다.
  name:string
}

type Player = User & { // extends대신 &으로 표시
}
const tom: Player = {
  name:'Tom' 
}
 
interface는 각각 만들어도 타입스크립트에서 자동으로 합쳐준다. (type은 못함..)
 
interface User{
  name: string
}
interface User{
  lastName: string
}
interface User{
  health: number
}

const tom: User = {
  name:'Tom',
  lastName:'Kim',
  health:10
} //interface를 따로써도 이렇게 합쳐서 쓸 수 있음(type에서는 못하는 기능)

 

추상클래스대신 인터페이스 사용하기
 
interface User{  
    firstName:string, //private property들을 사용하지 못한다.
    lastName:string
    sayHi(name: string):string  
    fullName():string
}
interface Human { 
  health:number
}
class Player implements User, Human { // extends대진 implement를 사용해준다 (extends는 js로 변환이 되지만 implement는 ts에서만 있는기능 코드가 더 가벼워진다.) / User와 Human을 함께 사용할 수 있다.
  constructor(
    public firstName:string,
    public lastName: string,
    public health: number
  ){}
  fullName(){
    return `${this.fullName} ${this.lastName}`
  }
  sayHi(){
    return `hello ${name}. My name is ${this.fullName()}`
  }
}
728x90
320x100

댓글