제네릭은 타입을 동적으로 설정할 수 있게 해주는 문법이다.
외부에서 타입을 주입하여, 동적으로 타입을 설정할 수 있기에 재사용이 가능한 컴포넌트를 구현하는데 있어서 핵심이다.
타입스크립트에서 가장 간단한 제네릭의 예이다.
// typescript v5.0.4
function printf<T>(i: T): void {
console.log(i);
}
printf<string>("Hi ~");
printf<number>(123);
printf("Zombie~"); // 제네릭 타입도 추론이 가능하다.
printf 함수의 인자는 어떤 타입의 변수든 인자로 받아 출력한다.
만약 제네릭을 사용하지 않았다면 인자인 변수 i의 타입은 any가 되었거나, 가능한 모든 타입을 union을 통해서 엮어내야 한다.
function printf(i: any): void {
console.log(i);
}
type Itype = string | number | object;
function printf(i: any): void {
console.log(i);
}
🥕 제네릭은 이와 같이 외부에서 타입을 주입받아 함수 내부에서 이 타입을 사용할 수 있게 해준다. 이를 통해서 함수 내부에 동적으로 타입을 주입시킬 수 있다.
🍎 또한, 타입스크립트에서 제네릭은 interface나 type alias에도 사용할 수 있다.
interface Movie<T> {
option: T;
}
const titanic: Movie<string> = {option: "4D"}
type Drama<T> = {
option: T;
}
type Option = {
runningTime: number;
}
const signal: Drama<Option> = {option: {runningTime: 500}};
🥝 그리고 역시, class에도 사용이 가능하다.
class Hero<T> {
constructor(private value: T){}
set setValue(tmp: T) {
this.value = tmp;
}
get getValue(): T {
return this.value;
}
}
const hero = new Hero<string>("park");
hero.setValue = "shin";
console.log(hero.getValue);
🍒 제네릭은 또한 extends 키워드를 통해 type이나 interface를 상속받을 수 있다.
interface Player {
age: number;
height: number;
}
function testPlayer<T extends Player>(person: T) {
console.log(person.age, person.height);
}
type Coach = {
talk: () => void;
career: string[];
}
function testCoach<T extends Coach>(person: T) {
person.talk();
person.career.forEach(el => {
console.log(el);
})
}
위와같이 상속을 통해서 추론이 불가능한 제네릭 타입의 단점을 일부 상쇄할 수 있다.
또한 keyof 나 typeof는 당연하게 제네릭에 사용될 수 있기에 제네릭은 활용도가 무궁무진하다.
https://www.typescriptlang.org/docs/handbook/2/generics.html#handbook-content
Documentation - Generics
Types which take parameters
www.typescriptlang.org
'TypeScript' 카테고리의 다른 글
Type only import, export에 대해서 (0) | 2023.07.05 |
---|---|
Typescript에서 Error 처리하기 (0) | 2023.06.22 |
typescript에서 typeof (with keyof) (0) | 2023.06.10 |
typescript에서의 class (0) | 2023.06.06 |
TypeScript의 enum에 대해서 (0) | 2023.05.19 |