개발
typescript interface/type
kwony
2022. 9. 7. 20:30
javascript 에선 객체 타입이 따로 존재하지 않아 받은 객체의 모양을 알 수 없었는데 타입스크립트에서는 interface와 type을 이용해서 객체의 형태를 유추 할 수 있게 됐다. 오랜 기간 javascript 로만 프로젝트를 진행 했었는데 typescript의 interface 와 type 덕분에 런타임 에러를 확 줄일 수 있었다.
Interface
Car라는 interface를 사용했고 showCarInfo 함수에 정보를 노출하게 했다. 특정 객체만 받도록 형태를 지정할 수 있게 됐다.
interface Car {
name: string,
color: string
}
function showCarInfo(car: Car) {
console.log(car.name)
console.log(car.color)
}
interface는 java의 class 처럼 상속을 할 수 있다. 중복된 property가 많다면 상속을 이용해서 처리하자.
interface SuperCar extends Car {
price: number
}
function showSuperCarInfo(car: SuperCar) {
console.log(car.name)
console.log(car.color)
console.log(car.price)
}
type
interface 랑 비슷한 역할을 하고 사용법도 비슷하다. 선언시 '=' 이 들어간다는 점만 다르다.
type Blog = {
name: string,
}
const blog: Blog = {
name: "아는 개발자"
}
type 은 여러개를 조합해서 사용 할 수 있는 기능이다. 아래 코드처럼 Blog 와 BlogOwner 라는 타입을 조합해 blogInfo 라는 변수를 만들 수 있다. java 의 interface 개념을 type에 적용한 것 같다. 여기서는 함수 뿐만 아니라 변수도 가능하니 정확히는 코틀린의 interface와 유사하고 보는 것이 맞겠다.
type Blog = {
name: string,
}
type BlogOwner = {
ownerName: string
}
const blogInfo : Blog & BlogOwner = {
name: "아는 개발자",
ownerName: "kwony"
}