티스토리 뷰

웹 개발/Typescript

Generic 기본

투자유v 2022. 1. 8. 16:54
728x90
// generic vs. any
function hello(message: any): any {
  return message;
}

console.log(hello('Hyun').length);
console.log(hello(33).length)


function helloGeneric<T>(message: T): T {
  return message;
}

console.log(helloGeneric<string>('Hyun').length); // T는 string
console.log(helloGeneric('Hyun').length); // T는 'Hyun'
console.log(helloGeneric<number>(33).length); // T는 number
// any를 사용하면 못 잡던 error를 잡아 준다.
console.log(helloGeneric(33).length); // T는 33
// any를 사용하면 못 잡던 error를 잡아 준다.
// generic 기본
function helloBasic<T, U>(message: T, comment: U): T {
  return message;
}

helloBasic<string, number>("Hyun", 33);
helloBasic(33, 34);function helloBasic<T, U>(message: T, comment: U): T {
  return message;
}

helloBasic<string, number>("Hyun", 33);
helloBasic(33, 34);
// Generic Array & Tuple
const genericArray = <T>(message: T[]): T => {
  return message[0];
}

const genericTuple = <T, K>(message: [T, K]): T => {
  return message[0];
}
// Generic Function
interface IFunction {
  (message: string): string;
}

const helloIFunction: IFunction = (message: string): string => {
  return message;
};

type TFunction = (message: string) => string;

const helloTFunction: TFunction = (message: string): string => {
  return message;
};

interface IGFunction {
  <T>(message: T): T;
}

const IGfunc: IGFunction = <T>(message: T): T => {
  return message;
};

type TGfunction = <T>(message: T) => T;

const TGfunc: TGfunction = <T>(message: T): T => {
  return message;
};
// Generic Class
class Person<T, K> {
  constructor(private _name: T, private _age: K) {}
}

const p1 = new Person('Hyun', 33);
const p2 = new Person<string, number>('Hyun', 33);
// Generic extends - 제네릭에서의 타입 제한
class Person<T extends string | number> {
  constructor(private _name: T) {}
}

const p1 = new Person('Hyun');
const p2 = new Person(33);
const p3 = new Person(true); // Error
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함