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}</>
}