Generics, Any와 다른 점
function helloString(msg: string): string {
return msg;
}
function helloNum(msg: number): number {
return msg;
}
function hello(msg: any): any {
return msg;
}
console.log(hello('Jinju').length);
console.log(hello(26).length);
function helloGeneric<T>(msg: T): T {
return msg;
}
console.log(helloGeneric('Jinju'));
console.log(helloGeneric(true));
Generics Basic
- 한가지 타입보다 여러 가지 타입에서 동작하는 컴포넌트를 생성하는데 사용된다
- 제네릭이란 타입을 마치 함수의 파라미터처럼 사용하는 것
function helloBasic<T>(msg: T): T {
return msg;
}
helloBasic<string>('Jinju');
helloBasic(26);
function byeBasic<T, U>(message: T, comment: U): T {
return message;
}
byeBasic<string, number>('Jinju', 26);
Generics Array & Tuple
function helloArr<T>(message: T[]): T {
return message[0];
}
helloArr(['Hello', 'World']);
helloArr(['Hello', 5]);
function helloTuple<T, K>(message: [T, K]): T {
return message[0];
}
helloTuple(['Hello', 'World']);
helloTuple(['Hello', 'World']);
Generics Function
type funcGen1 = <T>(msg: T) => T;
const helloFunc: funcGen1 = <T>(msg: T): T => {
return msg;
}
interface funcGen2 {
<T>(msg: T): T;
}
const helloFunc2: funcGen2 = <T>(msg: T): T => {
return msg;
}
- 기존 함수 타이핑 하는 방법에 Generics를 얹었음
Generics Class
- 클래스에서 Generics을 선언하고 사용하는 법
class Person<T, K> {
private _name: T;
private _age: K;
constructor(name: T, age: K) {
<this._name = name;
this._age = age;
}
}
new Person('Jinju', 26);
Generics with extends
class PersonExtends<T extends string | number> {
private _name: T;
constructor(name: T) {
this._name = name;
}
}
new PersonExtends(true);
- extends를 이용해서 Generics의 범위를 지정해준다