The difference between types and interfaces in TypeScript used to be more clear, but with the latest versions of TypeScript, they’re becoming more similar.
Interfaces are basically a way to describe data shapes, for example, an object.
Type is a definition of a type of data, for example, a union, primitive, intersection, tuple, or any other type.
타입스크립트가 버전업데이트가되면서 기존의 더 구분되었던 인터페이스와 타입의 관계가 점점 비슷해지고잇다.
인터페이스는 기본적으로 자료(형)의 모양을 나타내는 방법인데 예시로는 객체를 나타낼떄이다.
타입은 자료형의 정의다. 그 예로 데이터의 합집합, 원시형, 교집합, 튜플 기타등등..
타입스크립트를 배우면서 Type과 Interface 는 매우 유사하기에 타입과 인터페이스의 차이와 사용 예시를 알아보려고한다. 🙃
#인터페이스와 타입의 선언
//typescript
interface AnimalInterface{
skintype:string
age:number
}
interface MamaliaInterface extends PeopleInterface {
detailedspecies:string
}
type AnimalType ={
skintype:string
age:number
}
type MamaliaType = AnimalType & {
detaildspecies:string
}
#인터페이스의 선언적확장
interface Animal{
skintype:string
}
interface Animal{
age:number
}
// =>Animal { skintype:string, age:number}
=> 인터페이스는 같은이름으로 선언시 기존선언에서 확장된다.
type Animal= {
skintype:string
}
type Animal={
age:string
}
// => error: duplicate identifier 'Animal' 이미 Animal 타입이 선언되어있음
#computed value사용
type names = 'firstName' | 'lastName'
type NameTypes = {
[key in names]: string
}
interface NameInterface {
// error
[key in names]: string
}
type은 가능하지만 interface는 불가능하다.
몇가지 차이점이 있더라도 타입과 인터페이스는 엄~~청나게 유사하다고 할수있다. 사용시 특히 협업간에 프로젝트 전반에서 type 과 interface는 사용하기에 앞서 통일성있는 규칙을 먼저 정해야 할것같다. 개인적으로는 확장성 이나 타입의 확장성의 어려움등을 생각해보면 필자라면 interface 를 선호할거같다.