Frontend/TypeScript

[ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ(TypeScript) ] Incorrect (variable) is specified more than once, so this usage will be overwritten ์—๋Ÿฌ ํ•ด๊ฒฐํ•˜๊ธฐ

YWTechIT 2022. 12. 28. 19:00
728x90

๐Ÿ“ Incorrect (variable) is specified more than once, so this usage will be overwritten ์—๋Ÿฌ ํ•ด๊ฒฐํ•˜๊ธฐ

typescript๋กœ ์ž‘์—…ํ•˜๋‹ค ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์˜ค๋ฅ˜๋ฅผ ๋งˆ์ฃผํ–ˆ๋‹ค.

 

error-image

 

์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ ์›์ธ์€ getListHref๋ฅผ props๋กœ ๋‚ด๋ ค์ค€ ์œ„์น˜๊ฐ€ ์ž˜๋ชป๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์ธ๋ฐ, ๋ฐ”๋กœ {...props} ์•ž์— ์„ ์–ธํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ํ•˜๋‹จ์˜ AS-IS์ฝ”๋“œ๋ฅผ ์‚ดํŽด๋ณด๋ฉด {...props} ์•ž์— getListHref๋ฅผ ์„ ์–ธํ–ˆ๋Š”๋ฐ, ์ด๊ฒƒ์€ ์˜๋ฏธ๊ฐ€ ์—†๋‹ค. ์™œ๋ƒํ•˜๋ฉด ...props๋กœ ๋‚ด๋ ค์˜ค๋Š” getListHref์„ ์ตœ์ข…์ ์œผ๋กœ ์ ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ฒ˜์Œ์— ์„ ์–ธํ•œ getListHref๋ฅผ ํ•ญ์ƒ overrideํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.์ด๋Ÿด ๋•Œ๋Š” TO-BE ์ฝ”๋“œ์ฒ˜๋Ÿผ ๋‚ด๊ฐ€ ์ ์šฉํ•˜๊ณ  ์‹ถ์€ getListHref๋ฅผ {...props} ๋’ค์— ์„ ์–ธํ•ด์ฃผ๋ฉด ์˜ค๋ฅ˜๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

// AS-IS
export function createHeader({ width }: { width: SemanticWIDTHS }) {
  return function Header(props: ComponentProps<typeof HeaderBase>) {
    const getListHref = (queries: string) => `?${queries}`

    return <HeaderBase getListHref={getListHref} {...props} />  // 'getListHref' is specified more than once, so this usage will be overwritten.
  }
}

// TO-BE
export function createHeader({ width }: { width: SemanticWIDTHS }) {
  return function Header(props: ComponentProps<typeof HeaderBase>) {
    const getListHref = (queries: string) => `?${queries}`

    return <HeaderBase {...props} getListHref={getListHref} />
  }
}
728x90

์ž˜ ์ดํ•ด๊ฐ€ ๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ๋‹ค์Œ ์ฝ”๋“œ๋ฅผ ๋ณด์ž. Bad์— ์„ ์–ธํ•œ otherInfo.age๋Š” ์ ์šฉ๋˜์ง€ ์•Š๋Š”๋‹ค. ์™œ๋ƒํ•˜๋ฉด ...myInfo์˜ property๊ฐ€ ์ตœ์ข…์ ์œผ๋กœ ๋ฎ์–ด์”Œ์šฐ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๊ทธ๋ž˜์„œ, age๋ฅผ ํฌํ•จํ•œ name๊ณผ address ๋ชจ๋‘ ...myInfo๋กœ ์„ค์ •์ด ๋œ๋‹ค. ๋ฐ˜๋Œ€๋กœ Good์€ ์–ด๋–จ๊นŒ? age์™€ name ๋ชจ๋‘ otherInfo์—์„œ ์„ ์–ธํ•œ ๊ฐ’์ด ์ ์šฉ๋œ๋‹ค. ์™œ๋ƒํ•˜๋ฉด ...myInfo๊ฐ€ ์ œ์ผ ๋จผ์ € ์„ ์–ธ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฐ๊ณผ์ ์œผ๋กœ ๋งˆ์ง€๋ง‰์— ์„ ์–ธํ•œ age์™€ name์ด ์ ์šฉ๋œ๋‹ค.

const myInfo = {
  age: 28,
  name: 'ted',
  address: 'Hwaseong',
}

// Bad
const otherInfo = {
  age: 25, // This spread always overwrites this property.
  ...myInfo,
}

๐Ÿ‘‰๐Ÿพ otherInfo :>>  { age: 28, name: 'ted', address: 'Hwaseong' }โ€ˆ

// Good
const otherInfo = {
  ...myInfo,
  age: 25,
  name: 'jenny',
}

๐Ÿ‘‰๐Ÿพ otherInfo :>>  { age: 25, name: 'jenny', address: 'Hwaseong' }

 

Reference

  1. microsoft / Typescript #38525
  2. MDN - Spread_syntax
๋ฐ˜์‘ํ˜•