728x170
🤳TypeScript type과 interface의 공통점과 차이점
interface PeopleInterface {
name: string
age: number
}
const me1: PeopleInterface = {
name: 'yc',
age: 34,
}
type PeopleType = {
name: string
age: number
}
const me2: PeopleType = {
name: 'yc',
age: 31,
}
- type과 interface는 객체의 타입을 지정하는 공통점이 있다.
👀TypeScript type과 interface의 차이점
interface
interface PeopleInterface {
name: string
age: number
}
interface StudentInterface extends PeopleInterface {
school: string
}
type
type PeopleType = {
name: string
age: number
}
type StudentType = PeopleType & {
school: string
}
- 확장하는 방식에서 차이가 있습니다.
- 선언적 확장이 가능하다.
- interface 병합을 해서 사용이 가능하다.
- type 병합이 안된다
- interface는 객체에만 사용이 가능하다.
interface FooInterface {
value: string
}
type FooType = {
value: string
}
type FooOnlyString = string
type FooTypeNumber = number
// 불가능
interface X extends string {}
- computed value의 사용
- type은 가능하지만 interface는 불가능 중요!!
type names = 'firstName' | 'lastName'
type NameTypes = {
[key in names]: string
}
const yc: NameTypes = { firstName: 'hi', lastName: 'yc' }
interface NameInterface {
// error
[key in names]: string
}
👏성능을 위해서는 interface를 사용하는 것이 좋다.
라는 취지의 문서를 본적이 있는데, 한번 읽어 보는것을 추천해드립니다.
https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections
Interfaces create a single flat object type that detects property conflicts, which are usually important to resolve! Intersections on the other hand just recursively merge properties, and in some cases produce never.
그리드형
'Node.js & TypeScript' 카테고리의 다른 글
개발자라면 알아야할 NVM 개념 & 설치 & 사용법 (1) | 2024.04.15 |
---|---|
GraphQL Express Apollo-Server Mysql 서버 구축 (12) | 2023.03.29 |
[TypeScript] 타입스크립트 타입정의 (6) | 2022.11.11 |
[Typescript] 적용 Node.js 사용하기 (12) | 2022.11.08 |
Node.js Express 정적(static) Public 폴더 사용하기 (3) | 2022.10.30 |