Languages
Typescript Basic : 인터페이스
Korean Eagle
2020. 5. 13. 13:33
728x90
1. 인터페이스는 객체타입을 지정하지 않았을 때 any로 퉁치는 것을 방지하기 위해서 사용한다.
const post = {
title: 'A good post',
content: 'great post and great article'
}
const printPost = (postToPrint: { title: string, content: string }) => {
return `${postToPrint.title} with ${postToPrint.content}`
}
console.log(printPost(post))
1-1 위의 코드의 printPost함수의 postToPrint라는 인자는 { }를 통해 type을 지정했는데 이 부분이 없으면 그냥 any다.
1-2 그래서 저렇게 길게 타입을 지정했는데 여간 귀찮은 게 아니다. 이 객체 타입을 쓸 때 마다 이렇게 해줘야 한다.
1-3 이걸 간단하게 하려는 게 interface이다.
1-4 아래 처럼 interface를 도입하면 간단하게 어떤 형을 사용하려고 했는지 쉽게 예측할 수 있게 되고 간결해 진다.
1-5 인터페이스는 모든 구성요소가 일치해야 에러가 발생하지 않는다. 일부만 일치한다고 넘어가는 일은 없다.
interface Post {
title: string
content: string
}
const post: Post = {
title: 'A good post',
content: 'great post and great article'
}
const printPost = (postToPrint: Post) => {
return `${postToPrint.title} with ${postToPrint.content}`
}
console.log(printPost(post))
2. Typescript는 Java와 동일하게 멀티 인터페이스를 지원한다.
2-1 문법이 Java와 거의 유사하다.
// Coach.ts 파일
export interface Coach {
getDailyWorkout(): string;
}
// BaseballCoach.ts 파일
import { Coach } from './Coach'
export class BaseballCoach implements Coach {
getDailyWorkout(): string {
return "You have to hit 100 balls every day"
}
}
// GolfCoach.ts 파일
import { Coach } from './Coach'
export class GolfCoach implements Coach {
getDailyWorkout(): string {
return "swing 1000 times every day"
}
}
// 실행 파일 Driver.ts
import { BaseballCoach } from './BaseballCoach'
import { GolfCoach } from './GolfCoach'
import { Coach } from './Coach'
let golfCoach: GolfCoach = new GolfCoach()
let baseballCoach: BaseballCoach = new BaseballCoach()
let coaches: Coach[] = []
coaches.push(golfCoach)
coaches.push(baseballCoach)
coaches.forEach(coach => console.log(coach.getDailyWorkout()))
// 실행 결과
$ node Driver.js
swing 1000 times every day
You have to hit 100 balls every day
728x90