function 함수<MyType, MyType2>(x: MyType[], y: MyType2[]): MyType {
return x[0];
}
let x = 함수<number, string>([1, 2], ["3", "4"]);
// Generic 사용하지 않았을 때
function 함수(x: unknown[]) {
return x[0];
}
let a = 함수([1, 2]);
// a의 타입은 number가 아니라 unknown
// 연산 하려면 narrowing 해야함
console.log(a + 1); // 에러
// Generic을 사용했을 때
function 함수2<MyType>(x: MyType[]): MyType {
return x[0];
}
let b = 함수2<number>([1, 2]);
console.log(b + 1);
Generic 타입 제한을 둘 수 있다.
function 함수<MyType extends number>(x: MyType): number {
// 연산할 때 narrowing 할 필요 없음
return x + 1;
}
아래와 같이 커스텀 타입에도 적용 가능하다
interface LengthCheck {
length: number;
}
function 함수<MyType extends LengthCheck>(x: MyType): number {
// 연narrowing 할 필요 없음
return x.length;
}
클래스에서 generic을 사용할 땐, 클래스명 오른쪽에 타입을 적는다.
class 클래스<T> {
name;
constructor(a: T) {
this.name = a;
}
}
let a = new 클래스<string>("John");
console.log(typeof a.name); // 출력: string