제네릭이란 타입을 마치 함수의 파라미터처럼 사용하는 것이다.
- 위의 사진이 제네릭을 사용하는 이유이다.
- 저렇게 기존의 함수를 재사용하기위해 유니온타입을 계속 지정해주기 귀찮으니 제네릭을 사용하는 것이다.
→ 제네릭을 사용한다면 다음과 같이 바꿔줄 수 있다.
function getSize<T>(arr: T[]): number {
return arr.length;
}
const arr1 = [1, 2, 3];
getSize<number>(arr1);
const arr2 = ["a", "b", "c"];
getSize(arr2); //위와 같이 제네릭은 생략 가능하다.
const arr3 = [false, true, false];
getSize<boolean>(arr3);
const arr4 = [{}, {}, { name: "tim" }];
getSize<object>(arr4);
- 위와같이 제네릭은 생략 가능하지만, 유지보수의 관점으로 적어주는 것이 좋다.
- T는 타입파라미터라고 부른다.
추가 예시1
function getItemArray(arr: any[], index: number): any {
return arr[index];
}
function pushItemArray(arr: any[], item: any): void {
arr.push(item);
}
const techStack = ['js', 'react'];
const nums = [1, 2, 3, 4];
getItemArray(techStack, 0); // 'js'
pushItemArray(techStack, 'ts'); // ['js', 'react', 'ts']
getItemArray(nums, 0); // 1
pushItemArray(nums, 5); // [1, 2, 3, 4, 5];
→ 제네릭을 사용한다면 다음과 같이 바꿔줄 수 있다.
function getItemArray<T>(arr: T[], index: number): T {
return arr[index];
}
function pushItemArray<T>(arr: T[], item: T): void {
arr.push(item);
}
const techStack = ['js', 'react'];
const nums = [1, 2, 3, 4];
getItemArray(techStack, 0); // 'js'
pushItemArray<string>(techStack, 'ts'); // ['js', 'react', 'ts']
// pushItemArray<number>(techStack, 123); // Error
getItemArray(nums, 0); // 1
pushItemArray(nums, 5); // [1, 2, 3, 4, 5];
추가 예시2
interface Mobile<T> {
name: string;
price: number;
option: T;
}
const m1: Mobile<{ color: string; coupon: boolean }> = {
name: "s21",
price: 1000,
option: {
color: "red",
coupon: false,
},
};
const m2: Mobile<string> = {
name: "s21",
price: 1000,
option: "good",
};
제네릭 타입 변수
function printOut<T>(input: T): T {
console.log(input.length); // Error: T doesn't have .length
return input;
}
- 아직 T가 string 혹은 array가 될지 명시되지않았는데 length라는 함수를 호출해주기에 오류가 난다.
function printOut<T>(input: T[]): T[] {
console.log(input.length);
return input;
}
printOut([1, 2, 3]);
- 다음과 같은 방법으로 해결해줄 수 있다.
제네릭 제약 조건
function printOut<T>(input: T): T {
console.log(input.length); // Error: T doesn't have .length
return input;
}
- 인터페이스의 확장으로도 위와 같은 에러를 해결할 수 있다.
interface LengthWise {
length: number;
}
function printOut<T extends LengthWise>(input: T): T {
console.log(input.length);
return input;
}
// printOut(10); // Error, 숫자 타입에는 `length`가 존재하지 않으므로 오류 발생
// printOut({ length: 0, value: 'hi' }); // `input.length` 코드는 객체의 속성 접근과 같이 동작하므로 오류 없음
'내일배움캠프[4기_Reac트랙] > [원격]TS' 카테고리의 다른 글
9. 타입 추론 (0) | 2023.01.17 |
---|---|
7. interface & Intersection Type (0) | 2023.01.16 |
6. Union 타입 / Type Alias (0) | 2023.01.16 |
5. enum 타입 (0) | 2023.01.16 |
4. 함수타입 (0) | 2023.01.16 |