728x90
728x90
인터페이스(Interface)
들어가며
- 타입스크립트(TypeScript)의 인터페이스(Interface) 타입에 대해 정리해본다.

인터페이스(Interface)
개념
- 객체의 구조를 정의하는 데 사용되는 타입
- 객체가 가져야 할 속성, 그 속성의 타입, 그리고 메서드를 지정할 수 있다.
- 자바스크립트에는 존재하지 않으며, 타입스크립트에서 사용 가능하다.
- 코드의 가독성 및 유지보수를 쉽게 하고, 타입 안전성을 높여준다.
주요 기능
- 객체가 특정 속성들을 반드시 가지고 있어야 하는 구조를 정의할 수 있다.
- 특정 속성은 선택적으로 포함될 수 있도록 정의할 수 있다.
- 예)
age?: number;
- 예)
- 함수의 매개변수와 반환값의 타입도 인터페이스로 정의할 수 있다.
- 클래스는 인터페이스를
implements
키워드를 통해 구현할 수 있다.- 예)
class Dog implements Animal {}
- 예)
- 인터페이스는 여러 개를 상속받아 결합할 수 있다.
사용하기
기본 문법
- 객체가 가져야 할 속성, 그 속성의 타입, 그리고 메서드를 지정할 수 있다.
interface Person { name: string; age: number; greet(): void; // 메서드 } const person: Person = { name: 'John', age: 30, greet() { console.log('Hello!'); } }; person.greet(); // "Hello!"
인터페이스는 객체(Object)와 다르게 중괄호({ })안 각 항목의 문장의 끝에 쉼표(,)가 아닌 세미콜론(;)을 넣는다.
선택적 속성
?
를 사용하여 특정 속성을 선택적으로 정의할 수 있다.
interface Person { name: string; age?: number; // 선택적 속성 } const person1: Person = { name: 'Alice' }; // age 속성은 없어도 된다. const person2: Person = { name: 'Bob', age: 25 };
함수 타입 정의
- 인터페이스는 함수 타입도 정의할 수 있다.
interface Add { (a: number, b: number): number; } const add: Add = (x, y) => x + y; console.log(add(10, 20)); // 30
클래스와 인터페이스
- 클래스(Class)는 인터페이스를 구현할 수 있다.
implements
키워드를 이용한다.- 인터페이스를 구현한 클래스는 반드시 그 인터페이스에서 정의한 모든 속성과 메서드를 가져야 한다.
interface Animal { name: string; makeSound(): void; } class Dog implements Animal { name: string; constructor(name: string) { this.name = name; } makeSound() { console.log('Woof!'); } } const dog = new Dog('Buddy'); dog.makeSound(); // "Woof!"
인터페이스 확장하기
- 인터페이스는 다른 인터페이스를 상속받아 확장할 수 있다.
extends
키워드를 이용한다.
interface Animal { name: string; } interface Dog extends Animal { breed: string; } const myDog: Dog = { name: 'Max', breed: 'Labrador' };
함께 보기
[TypeScript] 인터페이스(Interface)와 타입 별칭(Type Alias) 비교
인터페이스(Interface)와 타입 별칭(Type Alias) 비교들어가며인터페이스(Interface)와 타입 별칭(Type Alias)은 타입스크립트에서 타입을 정의하는 방법이다.타입스크립트(TypeScript)에서 인터페이스(In
dev-astra.tistory.com
참고 사이트
Handbook - Interfaces
How to write an interface with TypeScript
www.typescriptlang.org
728x90
728x90
'Programming > TypeScript' 카테고리의 다른 글
[TypeScript] 환경 변수 타입 설정하기 (3) | 2024.12.09 |
---|---|
[TypeScript] 클래스(Class) (0) | 2024.10.12 |
[TypeScript] 제네릭(Generic) (0) | 2024.10.12 |
[TypeScript] Zod 라이브러리 (0) | 2024.10.11 |
[TypeScript] 타입 가드(Type Guard) (0) | 2024.10.10 |
[TypeScript] 모듈 방식 사용하기 (0) | 2024.10.10 |
[TypeScript] 인터페이스(Interface)와 타입 별칭(Type Alias) 비교 (0) | 2024.10.09 |
[TypeScript] ! 연산자(Non-null Assertion Operator) (0) | 2024.08.20 |