티스토리 뷰

 

 

안녕하세요 동기 여러분! 오늘은 객체 타입 심화의 첫 번째 시간으로 Interface를 알아보고 Type과의 차이점은 무엇인지 알아보도록 하겠습니다.

 

 

 

 

 

Interfaces and Types

아래의 type과 interface의 코드를 보도록 합시다.

type StarcraftUnit = {
    name: string;
    HP: number;
}

const marine: StarcraftUnit = // 내용
interface StarcraftUnit  {
    name: string;
    HP: number;
}

const marine: StarcraftUnit = // 내용

두 코드를 봤을 때 가장 눈에 띄는 차이점은 키워드(type, interface)가 다르다는 것과 type에는 있는 =(equal) 표시가 interface에는 없습니다.

 

기능적으로는 두 키워드 모두 컴파일링 시 타입을 체크합니다. 그럼 도대체 무엇이 다른 걸까요?

 

가장 큰 차이점으로는 interface는 객체 타입에만 사용이 가능합니다. type은 객체, 원시 타입(string, boolean, number, defined, null, symbol) 등등에 사용이 가능합니다. 그렇다면 typeinterface보다 다재다능한데 왜 interface를 사용할까요?

 

interface는 객체 타입에만 사용이 가능하기 때문에 객체 지향형 프로그램에 적합합니다. 왜냐하면 객체 지향형 프로그램들에게는 타입화 된 객체들이 많이 필요하기 때문입니다. 더불어 type 재선언이 불가능하지만 interface는 가능합니다.

 


 

해봅시다!

라면을 끓이는 시간을 넣으면 어떠한 라면이 나오는지 알려주는 코드입니다.

interface RamyeonCookTime {
    time: number;
}

function noodleCookingLevel(totaltime: RamyeonCookTime) {
    if(totaltime.time > 210){
        console.log('불은 라면');
    } else if(totaltime.time = 210){
        console.log('적당한 라면');
    } else {
        console.log('꼬들한 라면');
    }
}

noodleCookingLevel({
    time: 210
})
  • interface로 RamyeonCookTime를 선언해주고
  • 함수 noodleCookingLevel을 만들어서 매개 변수로 totaltime에 타입 RamyeonCookTime을 선언해줍니다.
  • if문으로 각 상황을 설정하고 출력문을 적어줍니다.
  • 확인을 위해 noodleCookingLevel에 time 프로퍼티와 그의 값으로 210을 넣어봤습니다.

 

컴파일링과 실행

에러 없이 잘 작동합니다.

 


 

오늘의 느낌

이제 밥 먹기 1시간 남았다 힘내자 ㅠㅠ (필자는 16시간마다 밥을 먹는다.)

'TypeScript' 카테고리의 다른 글

[TypeScript] Deep Types  (0) 2022.01.23
[TypeScript] Interfaces and Classes  (0) 2022.01.23
[TypeScript] Narrowing After a Type Guard  (0) 2022.01.23
[TypeScript] Narrowing with else  (0) 2022.01.22
[TypeScript] Using in with Type Guards  (0) 2022.01.21
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함