더보기에 있는 링크와 이어집니다.
함수 타입
구문
// 기본 구문 : 함수의 매개변수와 반환 타입을 지정하는 호출 시그니처를 사용
interface MathOperation {
(a: number, b: number): number;
}
const add: MathOperation = (x, y) => x + y;
const subtract: MathOperation = (x, y) => x - y;
function operate(a: number, b: number, operation: MathOperation): number {
return operation(a, b);
}
// 출력 결과
console.log(add(5, 3)); // 출력: 8
console.log(subtract(5, 3)); // 출력: 2
응용
interface Calculator {
name: string; // 이름 타입
add: MathOperation; // 더하기 타입
subtract: MathOperation; // 빼기 타입
}
const calculator: Calculator = {
name: "Simple Calculator",
add: (x, y) => x + y,
subtract: (x, y) => x - y,
};
// 출력 결과
console.log(calculator.name); // 출력: "Simple Calculator"
console.log(calculator.add(10, 5)); // 출력: 15
console.log(calculator.subtract(10, 5)); // 출력: 5
인덱서블 타입
구문
//구문 : [key: KeyType]: ValueType 형태
interface StringArray {
[index: number]: string; // 인덱스는 숫자, 키값은 문자
}
let myArray: StringArray = ["Hello", "World"]; // 0번 인덱스 "Hello", 1번 인덱스 "World"
console.log(myArray[0]); // 출력: "Hello"
interface NumberDictionary {
[key: string]: number; // 인덱스는 문자, 키값은 숫자
length: number; // 추가적인 프로퍼티도 정의 가능
}
let myDictionary: NumberDictionary = { length: 5, width: 10 };
console.log(myDictionary["length"]); // 출력: 5
※ 주의 : 키 타입은 string 또는 number만 허용한다.
클래스 타입
구문
interface Person {
name: string;
age: number;
greet(): void;
}
// 클래스 타입 정의
class Employee implements Person {
name: string; // 필드
age: number;
constructor(name: string, age: number) { // 생성자
this.name = name;
this.age = age;
}
greet(): void { // 메서드 정의
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// 클래스 사용
const employee = new Employee("Alice", 30);
employee.greet(); // Hello, my name is Alice and I am 30 years old.
- 필드 정의: 클래스 내부에 속성을 정의할 때 name: string과 같이 타입을 명시
- 생성자: constructor를 사용하여 객체 생성 시 속성을 초기화
- 메서드 정의: 클래스 내부의 메서드에도 반환 타입을 명시
인터페이스 확장
구문
// 기존 인터페이스를 기반으로 새로운 속성이나 메서드를 추가하는 기능
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
let square = {} as Square;
square.color = "red";
square.sideLength = 15;
console.log(square);
'TS' 카테고리의 다른 글
| 함수(Function)[1] (0) | 2024.11.20 |
|---|---|
| Interface(3) (0) | 2024.11.19 |
| Interface (1) (0) | 2024.11.15 |
| Interface (0) | 2024.11.08 |
| TypeScript의 타입 (이전 글 추가) (0) | 2024.11.07 |