Generic
- 함수 parameter type을 parameter와 같이 넘겨주어 함수 내부에서 해당 parameter의 type을 알 수 있게 함 -> runtime 에러를 방지함
- 재사용성이 높은 Component를 만들 때 활용
- 여러가지 type에서 동작하는 Component 생성
- 보통 함수의 이름 뒤에 <>로 선언
장점
1. 잘못된 type이 들어올 수 있는 경우를 compile 단계에서 사전에 방지 -> runtime 시에 발생하는 에러는 debug에 시간이 더 많이 소요됨
2. 클래스 외부에서 type을 지정해주기 때문에 따로 type을 확인하고 변환해줄 필요가 없음 -> 프로그램 성능이 향상됨
3. 코드의 재사용성이 높아짐
type | description |
< T > | Type |
< E > | Element |
< K > | Key |
< N > | Number |
< V > | Value |
< R > | Result |
예시
function getText(text: any): any { //함수의 인자에 어떤 type이 들어갔고 어떤 값이 반환되는지 알 수 없음
return text;
}
function getText<T>(text: T): T { //parameter의 type을 함수에서 알 수 있음 -> 입력값과 출력값에 대한 검증 가능
return text;
}
getText<string>('hi'); //함수의 인자에 string type이 들어갔음을 함수에서 알 수 있음
function logText<T>(text: T): T {
console.log(text.length); // Error: T doesn't have .length
return text;
}
function logText<T>(text: T[]): T[] {
console.log(text.length); // generic type이 array이기 때문에 length를 허용
return text;
}
--------------------------------------
interface LengthWise {
length: number;
}
function logText<T extends LengthWise>(text: T): T {
console.log(text.length); // interface LengthWise를 상속 받으므로 length를 허용
return text;
}
Generic Interface
interface GenericLogTextFn<T> {
(text: T): T;
}
function logText<T>(text: T): T {
return text;
}
let myString: GenericLogTextFn<string> = logText;
Generic Class
class GenericMath<T> {
pi: T;
sum: (x: T, y: T) => T;
}
let math = new GenericMath<number>();
출처
http://www.tcpschool.com/java/java_generic_concept
https://st-lab.tistory.com/153
https://joshua1988.github.io/ts/guide/generics.html
'IT > Programming Language' 카테고리의 다른 글
[Python] 까먹을 만한 문법 정리 (0) | 2022.03.22 |
---|---|
[Python] switch -> match (0) | 2022.03.22 |
[Javascript] 비동기 처리 방식 (0) | 2022.02.20 |
[Javascript] closure (0) | 2022.02.20 |
[Javascript] var -> let, const (0) | 2022.02.19 |
댓글