-
TS GenericsJavaScript/TypeScript 2021. 6. 23. 19:36
제네릭 (Generics)
- 클래스 또는 함수 내부에서 사용할 타입을 외부에서 결정하는 기법
예제 - Generic와 Any 차이점 // function helloString(message: string): string { // return message; // } // function helloNumber(message: number): number { // return message; // } function hello(message: any): any { return message; } // 3 console.log(hello("Lee").length); // undefined console.log(hello(45).length); // function 함수명<T> (parameter: T): T function helloGeneric<T>(message: T): T { return message; } // 3 console.log(helloGeneric("Kim").length); // console.log(helloGeneric(35).length); (에러발생)
Generics 기본
function helloBasic<T>(message: T): T { return message; } // 타입을 직접 지정 // helloBasic<string>(39); (에러) helloBasic<string>("Yoo"); // 지정하지 않으면 추론된다 helloBasic(36);
Generics Array & Tuple
function helloArray<T>(message: T[]): T { return message[0]; } // function helloArray<string>(message: string[]): string const a = helloArray(["1", "2", "3"]); // 1 console.log(a); // function helloArray<string | number>(message: (string | number)[]): string | number helloArray(["Hello", 3]); function helloTuple<T, K>(message: [T, K]): T { return message[0]; } // function helloTuple<string, string>(message: [string, string]): string const c = helloTuple(["Hello", "World"]); // Hello console.log(c); // function helloTuple<string, number>(message: [string, number]): string helloTuple(["Hello", 5]);
Generics Function
type HelloFunctionGeneric1 = <T>(message: T) => T; const helloFunc1: HelloFunctionGeneric1 = <T>(message: T): T => { return message; }; interface HelloFunctionGeneric2 { <T>(message: T): T; } const helloFunc2: HelloFunctionGeneric2 = <T>(message: T): T => { return message; };
Generics Class
class Person1<T> { private _name: T; constructor(name: T) { this._name = name; } } // new Person1("Lee"); // constructor Person1<string>(name: string): Person1<string> new Person1<string>("Lee");
Generics with extends
class PersonExtends<T extends string | number> { private _name: T; constructor(name: T) { this._name = name; } } new PersonExtends('Lee'); new PersonExtends(39); // new PersonExtends(true); (에러 발생)
keyof & type lookup system
interface IPerson { name: string; age: number; } const person: IPerson = { name: 'Lee', age: 35, }; // IPerson[keyof Iperson] // => IPerson["name" | "age"] // => IPerson["name"] | IPerson["age"] // => string | number function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } // Lee console.log(getProp(person, 'name')); // 35 console.log(getProp(person, 'age')); function setProp<T, K extends keyof T>(obj: T, key: K, value: T[K]): void { obj[key] = value; } setProp(person, "name", "Kim"); // Kim console.log(getProp(person, 'name'));
'JavaScript > TypeScript' 카테고리의 다른 글
TS 클래스 (0) 2021.06.23 TS 인터페이스 (0) 2021.06.19 TS 컴파일러 (0) 2021.06.18 TS 타입 시스템 (0) 2021.06.17 TS 타입 (0) 2021.06.12