π₯
28μΌμ°¨
Part 4. TypeScript Essentials
Ch 7. Generics
Ch 7. Generics
νμ μ μ΅λν μμ λ²μλ‘ μ ν νλ κ²μ΄ μ’λ€!!! κ·Έλ κ² λ§λ€κΈ° μν΄ λ Έλ ₯νμ
// Generics vs 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); // any
console.log(hello(39).length); // any
function helloGeneric<T>(message: T): T {
return message;
}
console.log(helloGeneric("Mark").length); // string
console.log(helloGeneric(39)); // number
console.log(helloGeneric(true)); // boolean
// Generic Basic
function helloBasic<T, U>(message: T, comment: U): T {
return message;
}
helloBasic<string, number>("Mark", 39); // μ§μ O => νμ
μ ν
helloBasic(36, 39); // μ§μ X => νμ
μΆλ‘
// Generic Array & Tuple
function helloArray<T>(message: T[]): T {
return message[0];
}
helloArray(["Hello", "World"]); // string
helloArray(["Hello", 5]); // string | number
function helloTuple<T, K>(message: [T, K]): T {
return message[0];
}
helloTuple(["Hello", "World"]); // string, string
helloArray(["Hello", 5]); // string | number
// Generics Function
type HelloFunctionGeneric1 = <T>(message: T) => T;
const helloFunction1: HelloFunctionGeneric1 = <T>(message: T): T => {
return message;
};
interface HelloFunctionGeneric2 {
<T>(message: T): T;
}
const helloFunction2: HelloFunctionGeneric2 = <T>(message: T): T => {
return message;
};
// Generic Class
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);
new Person<string, number>("Mark", "age"); // π¨ Error
// Generics with extends
class PersonExtends<T extends string | number> {
private _name: T;
constructor(name: T) {
this._name = name;
}
}
new PersonExtends("Mark");
new PersonExtends(39);
new PersonExtends(true); // π¨ Error string | number λ§ κ°λ₯
// keyof & type lookup system
interface IPerson {
name: string;
age: number;
}
const person: IPerson = {
name: "Mark",
age: 39,
};
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
getProp(person, "name"); // string
getProp(person, "age"); // number
function setProp<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
setProp(person, "name", "Anna");