props에 대한 명세!
function myInfo(info: {name:string; pw:string}) {
return console.log(info);
}
type info = {
name: string;
age: number;
}
interface info {
name: string;
age: number;
}
interface InfoProps {
name: string;
age: number;
}
const myInfo: React.FC<InfoProps> = ({info}) => {
return (
<div>
{getInfo(info)}
</div>
)
}
FC 정의
경로 ) node_modules/@types/react/index.d.ts
type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
(props: P, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P> | undefined;
contextTypes?: ValidationMap<any> | undefined;
defaultProps?: Partial<P> | undefined;
displayName?: string | undefined;
}
<P = {}>
)(props: P, context?: any)
를 제외한 나머지 프로퍼티는 선택적으로 할당할 수 있다.ReactElement 정의
interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
type: T;
props: P;
key: Key | null;
}
type Key = string | number;
JSXElementConstructor 정의
type JSXElementConstructor<P> =
| ((props: P) => ReactElement<any, any> | null)
| (new (props: P) => Component<any, any>);
interface Info {
age: number;
}
const myAge = ({age}: Info): JSX.Element => {
return (
<div>
{getAge(age)}
</div>
)
}
const [check, setCheck] = useState(false);
setCheck(!check);
const [check, setCheck] = useState<boolean>(false);
setCheck(!check)
const [check, setCheck] = useState<boolean | null>(null);
if(check){
//로직~~
}
state에 객체가 포함된 경우
interface Comment {
comment: string;
username: string;
date: string;
}
const [comments, setComments] = useState<Comment[]>([]);
[
{
comment: "hi",
username: "kim",
date: "2022.12.05"
},
{
comment: "hello~",
username: "lee",
date: "2022.12.06"
}
]
const divRef = useRef<HTMLDivElement>(null);
return(
<>
<ChildComponent divRef={divRef} />
<div ref={divRef}>
useRef에도 타입을 명시하고 싶습니다!
</div>
</>
)
HTMLDivElement
: div용 타입HTMLAnchorElement
, HTMLButtonElement
, HTMLTableElement
등 여러 타입이 있다.<ChildComponent divRef={divRef} />
: 자식 컴포넌트에 props로 넘겨보았다.const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value)
};
return <input onChange={handleOnChange}/>
React.ChangeEvent
: change이벤트에 사용하는 타입HTMLInputElement
를 제네릭으로 넘겼다.이벤트타입Event
ChangeEvent
, FormEvent
, TouchEvent
, FocusEvent
, KeyboardEvent
, MouseEvent
, DragEvent
등const tryAgainMessage: JSX.Element = <p>다시 시도해주세요.</p>
//예시) 카카오 로그인을 위한 라이브러리 추가
declare global {
interface Window {
kakao: any;
}
}