1. Generics, Any 와 다른 점
function helloString(message: string): string {
return message;
}
function helloNumber(message: number): number {
return message;
}
function hello(message: any): any {
return message;
}
console.log(hello('Mark').length);
console.log(hello(39).length);
function helloGeneric<T>(message: T): T {
return message;
}
console.log(helloGeneric('Mark'));
console.log(helloGeneric(39));
console.log(helloGeneric(true));
2. Generics Basic
function helloBasic<T, U>(message: T, comment: U): T {
return message;
}
helloBasic<string, number>("Mark", 39);
helloBasic(36, 39);
3. Generics Array & Tuple
function helloArray<T>(message: T[]): T {
return message[0];
}
helloArray(['Hello', "World"]);
helloArray(["Hello", 5]);
function helloTuple<T, K>(message: [T, K]): T {
return message[0];
}
helloTuple(['Hello', 'world']);
helloTuple(['Hello', 5]);
4. Generics Function
type HelloFunctionGeneric1 = <T>(message: T) => T;
const HelloFunctionGeneric1: HelloFunctionGeneric1 = <T>(message: T) => {
return message;
};
interface HelloFunctionGeneric2 {
<T>(message: T): T;
}
const helloFunction2 : HelloFunctionGeneric2 = <T>(message: T) => {
return message;
};
5. Generics Function
class Person<T, K> {
private _name: T;
private _age: K;
constructor(name: T, age: K) {
this._name = name;
this._age = age;
}
}
new Person("Mark", 39);
6. Generics with extends
- extends ⇒ generic에서는 기존 상속의 의미와 조금 다름
class PersonExtends<T extends string | number> {
private _name: T;
constructor(name: T) {
this._name = name;
}
}
new PersonExtends("Mark");
new PersonExtends(39);
7. keyof & type lookup system
- type을 적절히 찾아내고 활용하는 시스템.(컴파일 타임의 타입을 정확하게 찾아낼 수 있는 방법
interface IPerson {
name: string;
age: number;
}
const person: IPerson = {
name: 'Mark',
age: 39,
};
type Keys = keyof IPerson;
const keys: Keys = "name";
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
getProp(person, 'age');
function setProp<T, K extends keyof T>(
obj: T,
key: keyof T,
value: T[keyof T],
): void {
obj[key] = value;
}
setProp(person, "name", "Anna");