Interface vs Type 타입을 지정하는 또 다른 방법

2023. 12. 21. 02:32·기술/TypeScript

 

1. Interface란?

인터페이스는 객체, 클래스, 함수 타입을 지정하는 또 다른 방법 중 하나이다. 

//객체 타입을 지정하는 여러가지 방법

let person: { name: string; age: number } = { name: 'John', age: 30 };

type TPerson = { name: string; age: number };
let person: TPerson = { name: 'John', age: 30 };

interface IPerson {
  name: string;
  age: number;
}
let person: IPerson = { name: 'John', age: 30 };

 

보통 인터페이스는  I 를 붙여 명명한다.

interface I인터페이스_이름 {
  속성?: 타입;
}

 

2. 타입과 인터페이스의 차이

type Team = "red" | "blue" | "yellow"
//타입이 특정값을 갖도록 제한할 수 있음

//인터페이스 : 오직 한 가지의 용도. 오브젝트의 모양을 정해줌
interface Player {
	nickname: string,
	team:Team //Team이 red,blue,yellow만 가능
}

인터페이스와 타입은 거의 유사하게 동작하는 것처럼 보이지만  몇가지 차이점이 있다.

type은 다시 열어 새 속성을 추가할 수 없는 반면 인터페이스는 확장 가능하다.

 

interface User {
	name:string
}

interface Player extends User { //굳이 언급 안해도 상속 가능
	//name:string
}

 

타입도 확장과 비슷하게 &(intersection) 을 사용하여 구현할 수 있는데 타입의 속성이 중복일때 차이가 있다. 

interface IAnimal { 
  name :string 
} 
interface IDog extends IAnimal { 
  legs :number //확장
}

type TAnimal = { 
  name :string 
} 
type TDog = TAnimal & { legs: number } //속성 합치기 

//인터페이스도 & 사용 가능
interface IStudent {
  name :string,
}
interface ISubject {
  age :number
}

let classtime :IStudent & ISubject = { name : 'kim', age : 90 }

인터페이스의 경우 중복 선언하면 타입을 합쳐준다.(상속한것과 동일하게 동작)

//인터페이스 중복 선언
interface IUser {
	firstName: string;
}
interface IUser {
	lastName: string;
}
const nemo:IUser {
	firstName: "nemo"
	lastName: "bim";
} //알아서 합쳐줌. 타입으로는 불가능

//중복선언시 에러
type TAnimal = { 
  name :string 
} 
type TAnimal = { 
  legs :number 
}

//속성이 중복되는건 에러
interface IAnimal { 
  name :string 
} 
interface IBug extends IAnimal { 
  name :number 
}

//&로 합치는데 속성값이 다른 경우
interface IAnimal { 
  name :string 
} 
interface Ibug { 
  name :number
} 

let 변수 :IAnimal & Ibug = { name : '거미' } //never
//key가 같고 타입이 다른 경우에는 never, 둘다 같은 경우에는 합쳐줌, 오류 없음!

 

저작자표시 비영리 변경금지 (새창열림)

'기술 > TypeScript' 카테고리의 다른 글

[우아한 타입 스크립트 with 리액트] 타입스크립트의 등장, 웹개발의 역사와 자바스크립트의 한계  (0) 2024.07.28
[에러] typescript import 오류 : Could not find a declaration file for module 모듈에 대한 선언 파일을 찾을 수 없습니다.  (0) 2024.03.18
여러 타입을 만족하는 하나의 타입, 타입 합치기(Intersection Type, union/&)  (1) 2023.12.19
readonly 타입 설정, 불변성을 갖도록 만들기  (0) 2023.12.19
타입 축약과 타입의 확정 (Type Aliases 별칭, Narrowing, Assertion)  (1) 2023.12.18
'기술/TypeScript' 카테고리의 다른 글
  • [우아한 타입 스크립트 with 리액트] 타입스크립트의 등장, 웹개발의 역사와 자바스크립트의 한계
  • [에러] typescript import 오류 : Could not find a declaration file for module 모듈에 대한 선언 파일을 찾을 수 없습니다.
  • 여러 타입을 만족하는 하나의 타입, 타입 합치기(Intersection Type, union/&)
  • readonly 타입 설정, 불변성을 갖도록 만들기
빔네모
빔네모
console.log("빔네모")
  • 빔네모
    bimnemo("개발")
    빔네모
  • 전체
    오늘
    어제
    • 기록 (152) N
      • 기술 (42) N
        • JavaScript (6) N
        • TypeScript (9)
        • React.js (10)
        • Next.js (0)
        • 라이브러리,도구 (4)
        • HTML,CSS (4)
        • CS (5)
        • BE (4)
      • 개발 (98)
        • 프로젝트 (0)
        • 트러블슈팅 (5)
        • 알고리즘(코딩테스트) (93)
      • 정보 (4)
      • 취미 (8)
        • 감상 (8)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
빔네모
Interface vs Type 타입을 지정하는 또 다른 방법
상단으로

티스토리툴바