TypeScript/타입스크립트 TypeScript

[타입스크립트] 함수호출 시그니처의 제네릭

Rainbow🌈Coder 2022. 4. 21. 12:17
728x90

 

function filter<T>(array: T[], f: (item: T) => boolean): T[] {
  let result = [];
  // tslint:disable-next-line: prefer-for-of
  for (let i = 0; i < array.length; i++) {
    let item = array[i];
    if (f(item)) {
      result.push(item);
    }
  }
  return result;
}
type Filter<T> = { (array: T[], f: (iter: T) => boolean): T[] };

let names = [{ 이름: "smith" }, { 이름: "kate" }, { 이름: "max" }];

//1. T는 number로 한정됨
console.log(filter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (_) => _ > 5)); //[ 6, 7, 8, 9, 10 ]

//2. T는 string으로 한정됨
console.log(filter(["a", "b", "ab", "b", "c"], (_) => _ !== "b")); //[ 'a', 'ab', 'c' ]

//3. T는 {이름:string}으로 한정됨
console.log(filter(names, (_) => _.이름.endsWith("h"))); //[ { '이름': 'smith' } ]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90