미니옵빠의 code stubs

TypeScript에서 함수 파라메터로 Destructured Object 사용하기 본문

Language/Typescript

TypeScript에서 함수 파라메터로 Destructured Object 사용하기

미니옵빠 2017. 6. 14. 20:25


이런 식으로 사용 가능.

filter는 정의된 파라메터 외 rest 형태로 받음. 이것도 객체 형태라 any로 밖에..


interface Param {

  startDate: string;

  endDate: string;

  metric: string | string[];

  bucket: string | string[];

  filter: any;

}


export async function getFunc({ startDate, endDate, metric = 'REQUESTED', bucket, ...filter } : Param): Promise<any> {

   ...

}


interface 안 쓰고 한 줄에 쓰려면 아래 article 참고


https://blog.mariusschulz.com/2015/11/13/typing-destructured-object-parameters-in-typescript#providing-default-values


const value = { foo: "bar" };

toJSON(value, { pretty: true });  // #1
toJSON(value, { });               // #2
toJSON(value);                    // #3

The function call #1 already works because all parameters are specified. In order to enable function call #2, we have to mark the pretty property as optional by appending a question mark to the property name within the type annotation. Additionally, the prettyproperty gets a default value of true if it's not specified by the caller:

function toJSON(value: any, { pretty = true }: { pretty?: boolean }) {
    const indent = pretty ? 4 : 0;
    return JSON.stringify(value, null, indent);
}

Finally, function call #3 is made possible by providing a default value of {} for the destructuring pattern of the settings object. If no settings object is passed at all, the empty object literal {} is being destructured. Because it doesn't specify a value for the prettyproperty, its fallback value true is returned:

function toJSON(value: any, { pretty = true }: { pretty?: boolean } = {}) {
    const indent = pretty ? 4 : 0;
    return JSON.stringify(value, null, indent);
}