React ์—์„œ Typescript ์‚ฌ์šฉ์‹œ ์ฐธ๊ณ ํ• ๋งŒํ•œ Typing ๊ธฐ๋ฒ•์„ ๊ธฐ๋กํ•œ ๊ณณ

React.HTMLArributes<[HTMLElement]>

ํ•œ Element์— ๋ถ€์—ฌ๋  ์†์„ฑ ๊ฐ’๋“ค์„ ๋ชจ๋‘ ์ฐธ์กฐํ• ๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ธฐ๋ณธ HTML ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์Šคํƒ€์ผ๋งํ•ด์„œ ์‚ฌ์šฉํ• ๋•Œ ์œ ์šฉํ•จ

export interface ITextButtonProps extends IProps, React.HTMLAttributes<HTMLDivElement> {
  text?: string | JSX.Element
}

์œ„์™€ ๊ฐ™์ด, []๋กœ ๊ฐ์‹ธ์ง„ ๋ถ€๋ถ„์— ํ•„์š”ํ•œ ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ๋„ฃ์œผ๋ฉด ๋œ๋‹ค.

ํ•˜์ง€๋งŒ ์œ„ ๋ฐฉ๋ฒ•์ด ํ†ตํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ, ์•„๋ž˜์™€ ๊ฐ™์ด ์—˜๋ฆฌ๋จผํŠธ ๋ณ„๋กœ ๊ตฌ๋ถ„๋œ ์†์„ฑ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

const CustomInput = ({ error, ...props }: React.InputHTMLAttributes<HTMLInputElement> & IProps) => {
  return (
    <div>
      <input
        {...props}}
      />
      <label
        htmlFor={props.id}
      >
        {props.placeholder}
      </label>
      <div>{error}</div>
    </div>
  )
}

React.[Event]Event<[HTMLElement]>

onChange๋‚˜, onSubmit ์˜ ์ฝœ๋ฐฑํ•จ์ˆ˜์— ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๋‹ค.

// onChange ์ฝœ๋ฐฑ
const onChangeText = (e: React.ChangeEvent<HTMLInputElement>) => {
    setErrorMsg('')
    setText(e.target.value)
}
 
// onSubmit ์ฝœ๋ฐฑ
const onClickComplete = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (text.length === 0) {
      setErrorMsg('๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”')
      return
    }
    const res = onClickCompleteCallback(text)
    if (typeof res === 'string') {
      setErrorMsg(res)
    }
}

as [Type]

์–ด๋– ํ•œ value์˜ ํƒ€์ž…์„ ํ•œ ํƒ€์ž…์œผ๋กœ ๊ฐ•์ œ๋กœ ์ธ์‹ ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

const handleResize = (e: UIEvent) => {
      const w = e.target as Window
      setScreenSize(calcCurrentScreen(w.innerWidth))
}

์‚ฌ์‹ค์€ ๋งค์šฐ ์ง€์–‘ํ•ด์•ผํ•  ๋ฐฉ๋ฒ•์ด๋‹ค. ํ•˜์ง€๋งŒ, Typing์ด ๋„ˆ๋ฌด ์˜ค๋ž˜ ๊ฑธ๋ ค ๊ฐœ๋ฐœ ์‹œ๊ฐ„์— ์ง€์žฅ์„ ๋ผ์น ๋•Œ ์–ด์ฉ” ์ˆ˜ ์—†์ด ์‚ฌ์šฉํ•œ๋‹ค.

Axios.isAxiosError

Axios๋ฅผ ์‚ฌ์šฉํ•œ API ํ†ต์‹ ์‹œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๊ฒฝ์šฐ, Axios์—์„œ ์—๋Ÿฌ๋ฅผ ๊ฐ์‹ธ์„œ throwํ•˜๋Š”๋ฐ, ์ด๋•Œ ์ด๊ฒƒ์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด AxiosError๋ผ๊ณ  ์ธ์‹์‹œ์ผœ์„œ Typing์— ๋ฌธ์ œ ์—†๋„๋ก ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

if (axios.isAxiosError(err)) {
    switch (err.response?.data.message) {
      case [Strings.ErrorMessageFromServer.EXCEED_NONMEMBER_MAX_PLAYLIST]:
        errorMessage = Strings.ErrorMessageToUser.EXCEED_NONMEMBER_MAX_PLAYLIST
        break
    }
}

children : React.ReactNode

Wrapper ์ปดํฌ๋„ŒํŠธ์™€ ๊ฐ™์ด ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ์‹ธ๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋งŒ๋“ค์—ˆ์„๋•Œ, children ๊ฐ’์„ ๋ฐ›์•„์„œ ๋ Œ๋”ํ•ด์ค˜์•ผํ•˜๋Š”๋ฐ, ์ด๋•Œ children์˜ ์†์„ฑ์€ React.ReactNode์ด๋‹ค.

export default function AppInit({ children }: { children: React.ReactNode }) {
    ...
    return <>{children}</>
}