-
[TypeScript] Interface 란?공부/TypeScript 2024. 3. 22. 14:41
Interface
- Ineterface는 상호 간에 정의한 약속(규칙)을 의미한다.
- 즉, 클래스 또는 함수 처럼 '틀'을 정의하여 타입을 강제하도록 사용할 수 있는 것이 Ineterface이다.
- 타입 스크립트의 Ineterface는 주로 객체 위주로 다룬다.
1. Type Alias 와 Interface 차이
//Type Alias로 지정 type Trim = { option : string } //Type Alias는 & 기호를 사용하여 객체를 합침 type Model = Trim & { name : string, color : string} let Car : Model = {name : 'Cybertruck', color : 'Silver', option : 'RangeExtender'} //interface로 Type 지정 interface Model { name : string, color : string, } interface Model { option : string, } let Car :Model = { name : 'Cybertruck', color : 'Silver', option : 'RangeExtender' }
- type문을 사용해서 타입을 정의하면 중복한 이름으로는 타입을 선언이 불가능하다.
- interface의 경우 중복선언이 가능하며, 중복선언시 두개의 타입이 합쳐진다. (extends와 동일하게 동작)
- &(intersection)을 Interface도 사용가능하지만 extends를 사용하는 경우 타입이 중복되면
오류메시지를 알려주지만, &은 경우에 따라 알려주지 않는 경우가 있다.
2. extends
// interface의 장점 extends로 복사 가능 interface Employee { name : string } interface CEO extends Employee { age : number, } let staff : Employee = {name : 'park'}
- class와 같이 Ineterface도 extends를 통해 Ineterface간 확장이 가능하다.
- extends 시에는 중복되는 속성이 Interface 간에 들어있다면 오류가 발생하게 된다.
// interface의 장점 extends로 복사 가능 interface Employee { name : string, age : number, } //error발생 interface CEO extends Employee { age : number, } let staff : Employee = {name : 'park'}
'공부 > TypeScript' 카테고리의 다른 글
[TypeScript] Public, Protected , Private 란? (0) 2024.03.28 [TypeScript] Rest / Spread / Destructuring 문법 (1) 2024.03.24 [TypeScript] Class 문법 Type지정하기 (0) 2024.03.21 [TypeScript]Literal Types, Readonly, const 정리 (0) 2024.03.19 [TypeScript] TypeAlias ? (0) 2024.03.19