본문 바로가기

개발/JavaScript

[TypeScript] Functions

 

콜 시그니처 Call Signatures

- parameter, return type을 정의한 type

type Add = (a:number, b:number) => number;

const add:Add = (a, b) => a + b;

 

 

오버로딩 Overloading 

- 함수가 서로 다른 여러 개의 콜 시그니처를 가질 때 발생

type Add = {
    (a:number, b:number) : number
    (a:number, b:string) : number
};

const add:Add = (a, b) => {
    if(typeof b === "string") return a;
    return a + b;
};

- 파라미터 개수가 다른 경우 option 파라미터 타입 명시

type Add = {
    (a:number, b:number) : number
    (a:number, b:number, c:number) : number
};

const add:Add = (a,b,c?:number) => {
    if(c) return a + b + c;
    return a+b;
};

add(1,2);
add(1,2,3);

- 오버로딩 예)

type Config = {
    path: string,
    state: object
};

type Push = {
    (path: string) : void
    (config: Config) : void
};

const push:Push = (config) => {
    if(typeof config === "string") {
        console.log(config);
    } else {
        console.log(config.path, config.state);
    };
};

 

 

다형성 Polymorphism

제네릭 Generic: 콜 시그니처 작성 시 확실한 타입을 모를 때 사용 -> any와 다른 점: type을 기억

type SuperPrint = {
    //(arr: number[]) : void
    //(arr: boolean[]): void
    //(arr: string[]) : void
    <T>(arr: T[]) : void // 제네릭 선언
}

const superPrint: SuperPrint = (arr) => {
    arr.forEach(i => console.log(i))
};

superPrint([1,2,3,4])
superPrint([true, false, true]);
superPrint(["a","b","c"]);
superPrint([1, 2, true, false, "bb"]);

제네릭 파라미터 배열의 타입

function superPrint<T>(a: T[]) {
    return a[0]
}
type SuperPrint = <T>(arr: T[]) => T

const superPrint: SuperPrint = (arr) => arr[0]

const a = superPrint([1,2,3,4])
const b = superPrint([true, false, true]);
const c = superPrint(["a","b","c"]);
const d = superPrint([1, 2, true, false, "bb"]);

제네릭 리턴 타입

- 2개 이상 제네릭 사용

type SuperPrint = <T, M>(arr: T[], b:M) => T

- 제네릭 활용

type Player<E> = {
    name:string
    extraInfo:E
}

type JajaExtra = {
    favFood: string
}

type JajaPlayer = Player<JajaExtra>

const jaja : JajaPlayer = {
    name:"jaja",
    extraInfo: {
        favFood:"cake"
    }
}

const tata: Player<null> = {
    name:"tata",
    extraInfo:null
}

 

- 다형성 이용 로컬스토리지 API 만들기

interface SStorage<T> {
    [key:string]:T
}

// local storage API
class LocalStorage<T> {
    private storage:SStorage<T> = {}
    set(key:string, value:T) {
        this.storage[key] = value;
    }
    remove(key:string) {
        delete this.storage[key]
    }
    get(key:string):T {
        return this.storage[key]
    }
    clear() {
        this.storage = {}
    }
}

const stringSrorage = new LocalStorage<string>(); // T: string 선언

stringSrorage.get("cat"); // get(key:string): string
stringSrorage.set("dog", "meong"); // set(key:string, value:string): void

const booleansStorage = new LocalStorage<boolean>();

booleansStorage.get("true"); // get(key:string): boolean

'개발 > JavaScript' 카테고리의 다른 글

[TS] Interfaces  (0) 2022.08.05
[TypeScript] Classes  (0) 2022.08.04
[TypeScript] Types  (0) 2022.08.04
[Node.js] Auth route, Logout Route  (0) 2022.07.22
[Node.js] login route  (0) 2022.07.22