TypeScript Generics

100pearlcent·2021년 8월 31일
0

TypeScript

목록 보기
6/6
post-thumbnail

Generics, Any와 다른 점


// 일정 로직을 반복하는 함수들

function helloString(msg: string): string {
	return msg;
}

function helloNum(msg: number): number {
	return msg;
}

// 이 경우 any타입을 사용하게 된다면
function hello(msg: any): any {
	return msg;
}

console.log(hello('Jinju').length);
console.log(hello(26).length); // Error

// 대신에 제네릭을 사용한다면
function helloGeneric<T>(msg: T): T {
 return msg;
}

console.log(helloGeneric('Jinju'));
// > T는 문자열이 아닌 'Jinju'라는 리터럴 타입이 된다
console.log(helloGeneric(true));

Generics Basic

  • 한가지 타입보다 여러 가지 타입에서 동작하는 컴포넌트를 생성하는데 사용된다
  • 제네릭이란 타입을 마치 함수의 파라미터처럼 사용하는 것
function helloBasic<T>(msg: T): T {
	return msg;
}

helloBasic<string>('Jinju');

helloBasic(26);
// 위처럼 제네릭을 지정해주지 않으면 T가 추론 됨
// 👉 function helloBasic<36>(message: 36): 36 {} 과 같음


// 여러 개 쓰는 것도 가능
function byeBasic<T, U>(message: T, comment: U): T {
	return message;
}

byeBasic<string, number>('Jinju', 26);

Generics Array & Tuple

// ✨ARRAY

// T의 배열로 들어온 값의 첫 번째 요소 리턴
function helloArr<T>(message: T[]): T {
	return message[0];
}

helloArr(['Hello', 'World']);
// function helloArrr<string>(message: string[]): string
// 'hello'가 리턴 됨

helloArr(['Hello', 5]);
// function helloArr<string|number>(message:(string|number)[]): string|number

// ✨TUPLE 
function helloTuple<T, K>(message: [T, K]): T {
	return message[0];
}

helloTuple(['Hello', 'World']);
// 배열과 같음

helloTuple(['Hello', 'World']);
// function helloTuple<string, number>(message:[string, number]): string

Generics Function

// type alias를 이용한 방법
type funcGen1 = <T>(msg: T) => T;

const helloFunc: funcGen1 = <T>(msg: T): T => {
	return msg;
}

// 인터페이스를 이용한 방법
interface funcGen2 {
	<T>(msg: T): T;
}

// 구현체
const helloFunc2: funcGen2 = <T>(msg: T): T => {
	return msg;
}
  • 기존 함수 타이핑 하는 방법에 Generics를 얹었음

Generics Class

  • 클래스에서 Generics을 선언하고 사용하는 법
class Person<T, K> {
  // 해당 타입의 유효범위 = 클래스 전체
	private _name: T;
	private _age: K;
	
	constructor(name: T, age: K) {
    	<this._name = name;
      	this._age = age;
    }
}

new Person('Jinju', 26);

Generics with extends

// string이나 number만 들어올 수 있는 T
class PersonExtends<T extends string | number> {
	private _name: T;

	constructor(name: T) {
    	this._name = name;
    }
}

new PersonExtends(true);
  • extends를 이용해서 Generics의 범위를 지정해준다

0개의 댓글