(1) 함수에서의 제네릭
(2) class 에서 제네릭
(3) 제네릭 확장
(4) interface/type 에서 제네릭
예제
type User = {
id: number;
name: string;
}
type Address = {
zipcode: number;
address: string;
}
함수에서의 제네릭 (1)
// 타입을 선언할 때
const pipOne = function(value: any): any {
return value;
}
const pipTwo = function<T>(value: T): T {
return value;
}
const pipThree = <T>(value: T): T => {
return value;
}
// 타입을 확정지을 때
let num = pipTwo(10);
let str = pipThree('A');
// 타입을 선언할 때
const pipObjectOne = <T>(obj: T): T => {
return obj;
}
// 타입을 확정지을 때
let po1 = pipObjectOne<User>({ id: 1, name: 'kim' });
함수에서의 제네릭 (2)
// [ 변수에 타입(함수타입) 지정 ]
// 두 코드는 같은 의미입니다.
let str: <T>(text: T) => T
let str2: { <T>(text: T): T }
// [ 타입(함수타입) 생성 ]
// 두 코드는 같은 의미입니다.
type func = <T>(text: T) => T;
interface func2 {
<T>(text: T): T;
}
// [ 변수에 함수 표현식 할당 ]
// 두 변수의 타입은 같은 의미입니다.
function myStrB<T>(text: T): T{
return text;
}
str = myStrB;
str2 = myStrB;
const myStrA_1: func = myStrB;
const myStrA_2: func2 = myStrB;
class 에서 제네릭
// 타입을 선언할 때
class Main<T, Config = {}> {
id;
obj;
constructor(id: T, obj: Config) {
this.id = id;
this.obj = obj;
}
getProperty(): Config {
return this.obj;
}
}
// 타입을 확정지을 때
const Perp = new Main('user', { zeneric: 1 });
제네릭 확장
// 타입을 선언할 때
function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
// 타입을 확정지을 때
getProperty(x, 'a');
getProperty(x, 'c');
interface/type 에서 제네릭
// 타입을 선언할 때
interface KeyPair<T, U> {
key: T;
value: U;
}
type ValuePair<T, U> = {
key: T;
value: U;
}
// 타입을 확정지을 때
let kv1: KeyPair<number, string> = { key: 1, value: 'kim' };
let kv2: KeyPair<number, number> = { key: 2, value: 12345 };