λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

πŸ’¬/γ…γ……γ…Œγ…‹γ…γ…… μ±Œλ¦°μ§€

28일차

πŸ₯•

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");

 

'πŸ’¬ > γ…γ……γ…Œγ…‹γ…γ…… μ±Œλ¦°μ§€' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

30일차  (0) 2022.03.18
29일차  (0) 2022.03.17
27일차  (0) 2022.03.17
26일차  (0) 2022.03.16
25일차  (0) 2022.03.15