728x90
728x90
🖥️ Interface 문법
타입스크립트에서 인터페이스(interface)는 코드를 구조화하고 타입을 정의하는데 사용된다. 인터페이스는 객체의 구조를 설명하며, 클래스, 함수 등에서 사용할 수 있다.
🖥️ Interface의 정의
interface Person {
name: string;
age: number;
email?: string; // 옵셔널 프로퍼티
sayHello(): void; // 메서드 정의
}
let person: Person = {
name: 'John',
age: 25,
sayHello() {
console.log('Hello!');
}
};
- 기본 인터페이스 구조 : 'interface' 키워드를 사용하여 인터페이스를 정의한다. 위의 코드에서 'Person' 인터페이스는 'name'과 'age' 두 개의 필수 프로퍼티와 'email' 은 옵셔널 하게 줄 수 있으며, sayHello 메서드를 가져간다.
- 인터페이스 사용 : 'Person' 인터페이스를 사용하여 객체를 선언할 때 해당 객체가 인터페이스의 요구 사항을 충족하는지 확인한다.
🖥️ Interface 확장
interface Employee extends Person {
jobTitle: string;
}
let employee: Employee = {
name: 'Alice',
age: 30,
jobTitle: 'Software Engineer',
sayHello() {
console.log('Hello from employee!');
}
};
- 인터페이스 확장 : 인터페이스는 다른 인터페이스를 확장할 수 없다. 위의 코드에서 'Employee' 인터페이슨느 'Person' 인터페이스를 확장하며, 새로운 'jobTitle' 프로퍼티를 추가한다.
🖥️ 함수에서의 interface 사용
interface MathOperation {
(x: number, y: number): number;
}
let add: MathOperation = (a, b) => a + b;
let subtract: MathOperation = (a, b) => a - b;
- 함수에서의 인터페이스 사용 : 함수의 타입을 정의하기 위해 인터페이스를 사용할 수 있다. 위의 코드에서 'MathOperation' 인터페이스는 두 개의 숫자를 받아 숫자를 반환하는 함수를 정의한다.
728x90
'👨💻 TypeScript' 카테고리의 다른 글
TypeScript - TypeScript never type (0) | 2024.03.04 |
---|---|
TypeScript - rest parameter / destructuring (0) | 2024.03.02 |
TypeScript - Class types (2) | 2024.02.27 |
TypeScript - DOM Manupulation (0) | 2024.02.26 |
TypeScript - Type alias (1) | 2024.02.25 |