스파이더 웹 개발

타입스크립트 - 제네릭 본문

JavaScript

타입스크립트 - 제네릭

스파이더웹 2022. 10. 16. 22:08
728x90
반응형

 

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

function helloNumber(message: number): number{
    return message;
}

function hello(message: any): any {
    return message;
}

//any의 경우 input에 따라 달라지는 코드를 구현할 수 없다
console.log(hello('Mark').length);
// console.log(hello(30).length);

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

//generic의 경우 input에 따라 다르게 코드를 구현할 수 있다
console.log(helloGeneric('Mark').length);
console.log(helloGeneric(30).toString);
console.log(helloGeneric(true).valueOf);
 

제네릭 기본

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

// helloBasic<string>(30); 컴파일에러
helloBasic<string>('Mark'); //제너릭 지정

helloBasic(36); //제너릭 추론
 

제네릭 배열/튜플

function helloArray<T>(message: T[]): T {
    return message[0];
}

helloArray(['Hello','World']);
helloArray(["hello",5]); //string | number

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

helloTuple(['Hello', 'World']);
helloTuple(["hello", 5]);
 

제네릭 클래스

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(40,30);
// new Person<String>(30); 컴파일 에러
 

제네릭 상속

class PersonExtends<T extends string | number> { 
    //T는 string과 number만 가능하다
    private _name: T;

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

// new PersonExtends(true); 컴파일 에러
new PersonExtends('Mark');
new PersonExtends(30);
 
 

 

 

728x90
반응형

'JavaScript' 카테고리의 다른 글

자바스크립트 전체 복습(3)  (0) 2022.10.15
자바스크립트 복습(2)  (0) 2022.10.14
자바스크립트 - 복습  (0) 2022.10.14
자바스크립트 - 제네릭  (0) 2022.10.11
타입스크립트 확장  (0) 2022.10.11
Comments