๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ์ƒํ™ฉ


์•„๋ž˜์™€ ๊ฐ™์€ ํƒ€์ž…์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž.

export type OrderStatus = 'pending' | 'new' | '...์ƒ๋žต';
export type Client = { user_id: number; company_name: string };

export type OrderFilterParams = {
  status: Array<OrderStatus>;
  client: Array<Client>;
  // ...์ƒ๋žต
};

 

ClientAndOrderFilter ์ปดํฌ๋„ŒํŠธ์—์„  "status" | "client" ๋‘ ์ข…๋ฅ˜์˜ ํƒ€์ž…์„ ๋ฐ›์•„ params[type] ํ˜•ํƒœ๋กœ OrderFilterParams ๊ฐ์ฒด์— ์ ‘๊ทผํ•ด์„œ ๊ฐ’์„ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ์ƒํ™ฉ์ด๋‹ค. 

interface ClientAndOrderFilterProps {
  setParams: Dispatch<SetStateAction<OrderFilterParams>>;
  params: OrderFilterParams;
  type: 'status' | 'client';
  // ...
}

 

ํ•˜์ง€๋งŒ ClientAndOrderFilter ์ปดํฌ๋„ŒํŠธ์—์„œ ์–ด๋–ค ์ข…๋ฅ˜์˜ type("status" | "client")์„ ๋ฐ›์„์ง€ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋Š” ์•Œ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— params[type] ํ˜•ํƒœ๋กœ ์ ‘๊ทผํ•˜๋ฉด ํƒ€์ž… ์ถ”๋ก ์ด ์ด๋ค„์ง€์ง€ ์•Š์•„ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๊ณ  ์žˆ๋‹ค. 

 

ํ•ด๊ฒฐ ๋ฐฉ์•ˆ


์•„๋ž˜์ฒ˜๋Ÿผ ์‹๋ณ„์ž ์˜์—ญ์—์„  type("status" | "client") Prop ํƒ€์ž…์œผ๋กœ T์˜ ์ œ์•ฝ ์กฐ๊ฑด์„ ์ง€์ •ํ•˜๊ณ , ๊ตฌํ˜„๋ถ€์—์„  T ํƒ€์ž…์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์กฐ๊ฑด๋ถ€ ํƒ€์ž…(OrderStatus[] | Client[])์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. 

// ๋ณ€๊ฒฝ ์ „ (๊ฐ key์— ํ• ๋‹น๋  ๊ฐ’์„ ๊ณ ์ •ํ•˜์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ ์ˆ˜์ • ํ•„์š”)
export type OrderFilterParams = {
  [key in OrderFilterType]?: Array<OrderStatus | ISODateString | ClinicLabType>;
};

// ๋ณ€๊ฒฝ ํ›„
export type OrderFilterParams = {
  status: Array<OrderStatus>;
  client: Array<Client>;
  startdate: Array<ISODateString>;
  enddate: Array<ISODateString>;
};
export type ListType = 'status' | 'client';

// OrderStatus[] / Client[] 2๊ฐ€์ง€ ์ข…๋ฅ˜์˜ ๋ฐฐ์—ด์„ ๋ฐ›์œผ๋ฏ€๋กœ ์ œ๋„ค๋ฆญ ์‚ฌ์šฉํ•ด์„œ ํƒ€์ž… ๊ฐ€๋“œ
// <T = ListType> ๋ถ€๋ถ„์€ ํƒ€์ž… ์‹๋ณ„์ž. "status" | "client"๋ฅผ T์˜ ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ ์ง€์ •
// Array<T extends ...> ๋ถ€๋ถ„์€ ํƒ€์ž… ๊ตฌํ˜„๋ถ€. T๋ฅผ "status"๋กœ ๋ฐ›์œผ๋ฉด OrderStatus[] ํƒ€์ž…์„ ๋ฆฌํ„ดํ•˜๊ณ  ๊ทธ ์™ธ์—” Client[] ํƒ€์ž… ๋ฆฌํ„ด
export type ListFilter<T = ListType> = Array<
  T extends 'status' ? OrderStatus : Client
>;

 

์ด์ œ params[type]์˜ ํƒ€์ž…์„ ListFilter<typeof type>์œผ๋กœ ์ง€์ •ํ•˜๋ฉด ํƒ€์ž… ์—๋Ÿฌ๊ฐ€ ํ•ด๊ฒฐ๋œ๋‹ค. โœจ

const clickHandler = (status: ListFilterStatus) => {
  setParams((prevParams) => {
    const params: ListFilter<typeof type> = prevParams[type];
    // ...
    return {
      ...prevParams,
      [type]: params.filter((param) => {
        /* ... */
      }),
    };
  });
};

 


๊ธ€ ์ˆ˜์ •์‚ฌํ•ญ์€ ๋…ธ์…˜ ํŽ˜์ด์ง€์— ๊ฐ€์žฅ ๋น ๋ฅด๊ฒŒ ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค. ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”
๋ฐ˜์‘ํ˜•