728x90
제네릭 클래스
class NumberList {
constructor(private list: number[]) {}
push(data: number) {
this.list.push(data);
}
pop() {
return this.list.pop();
}
print() {
console.log(this.list);
}
}
const numberList = new NumberList([1, 2, 3]);
numberList.pop();
numberList.push(4);
numberList.print();
- NumberList라는 클래스를 만들었다.
- private를 붙이면 필드를 따로 지정하지 않아도 되고, 생성자 함수 내에서도 별도로 this.~ 를 적을 필요가 없다.
- 따라서 private로 접근 제어한 파라미터인 list는 number가 들어 있는 배열로 외부와 파생 클래스에서는 접근할 수 없다.
- NumberList에는 push, pop, print라는 메서드가 존재한다.
- numberList라는 변수는 NumberList의 인스턴스로 [1, 2, 3]을 전달한다.
- 콘솔에 찍어보면 [1, 2, 4]가 정상적으로 나온다.
현재 list의 타입이 number[]이기 때문에 [1, 2, 3] 과 같은 number array만 해당 클래스를 사용할 수 있는데,
만약 string[]이나 boolean[]이라면 클래스를 사용할 수 없게 된다.
이 때 제네릭 클래스로 만들어주면 여러 타입의 리스트를 생성할 수 있는 범용적인 클래스를 정의할 수 있게 된다.
class NumberList<T> {
constructor(private list: T[]) {}
push(data: T) {
this.list.push(data);
}
pop() {
return this.list.pop();
}
print() {
console.log(this.list);
}
}
const numberList = new NumberList([1, 2, 3]);
numberList.pop();
numberList.push(4);
numberList.print();
const stringList = new NumberList(['a', 'b', 'c']);
stringList.pop();
stringList.push('d');
stringList.print();
- 간단하게 list의 타입을 타입 변수 T[]로 재정의하고, data도 T로 바꿔주면 된다.
**출처: 한 입 크기로 잘라먹는 타입스크립트 (인프런, 이정환 강사님)
728x90
'❔ TypeScript > 💭 한 입 크기 TypeScript' 카테고리의 다른 글
[TypeScript] 타입 조작 (0) | 2023.12.22 |
---|---|
[TypeScript] 프로미스와 제네릭 (0) | 2023.12.22 |
[TypeScript] 제네릭 인터페이스 (0) | 2023.12.21 |
[TypeScript] map, forEach 메서드 타입 정의하기 (0) | 2023.12.21 |
[TypeScript] 제네릭 활용 (1) | 2023.12.21 |