npx create-react-app 폴더명 --template typescript
하여 폴더 생성npm install @types/설치대상명
와 같이 @types/를 앞에 붙여 install 한다.
하위 컴포넌트로 props를 전달할 시
해당 컴포넌트에서 타입을 지정해주어야한다.
❗
function TodoItem({todo}:{todo:Todo}){
}
props 타입을 위와 같이 지정하는 경우는
props가 객체이기 때문에, 해당 객체의 todo에 타입을 지정한 것이다.
React.해당하는이벤트<해당하는위치> 로 타입을 지정해준다.
import React, { Dispatch } from 'react';
type Action=
{type:"SET_COUNT"; count:number;} |
{type:"SET_TEXT"; text:string;} |
{type:"SET_COLOR"; color:Color;} |
{type:"SET_GOOD";};
// dispatch를 위한 타입
// action 타입을 Dispatch의 제네릭으로 지정
type Sampledispatch= Dispatch<Action>
const SampleContext = ({children}:{children:React.ReactNode}) => {
const [state,dispatch]= useReducer(reducer,{
count: 0,
text: "",
color: 'pink',
isgood: true
})
return (
<SampleStateContext.Provider value={state}>
<SampleDispatchContext.Provider value={dispatch}>
{children}
</SampleDispatchContext.Provider>
</SampleStateContext.Provider>
);
};
children의 타입은 {children:React.ReactNode}
이다.
style의 타입은 React.CSSProperties
이다.
작성하면, 자동적으로 타입이 지정된다.
타입을 지정하고 싶을 시 아래와 같이 지정한다.
const [] =useState<number>(0)
useReducer(reducer,state)
npm install redux react-redux @types/react-redux
설치
① 스토어 생성하기
const store= createStore(리덕스모듈)
<Provider store={store}>
<App/>
</Provider>
리덕스 모듈은 액션타입 및 리듀서를 뜻한다.
const green= 0 as number
👉 타입단언. 위와 같이 작성하면 green변수의 타입은 number라는 선언이 된다.
타입 단언을 사용하면 타입 체커에게 오류를 무시하도록 한다.
ReturnType<typeof함수>
👉특정함수의 반환값을 추론
// 1. action type
// action.type이 string으로 추론되지 않고 "counter/이하"와 같이
// 실제 문자열 값으로 추론되도록 as const를 붙임
const INCREASE= "counter/INCREASE" as const;
const DECREASE= "counter/DECREASE" as const;
// 2. action 생성함수
const increase=()=>({type: INCREASE})
const decrease=()=>({type: DECREASE})
// action 객체 타입
type CounterAction= ReturnType<typeof increase> | ReturnType<typeof decrease>
// 3. reducer
function counter(state,action:CounterAction){
}
export default counter;
위와 같이 함수의 반환값을 type으로 줄 때 사용한다.
위의 type CounterAction은
type CounterAction= {type: INCREASE} | {type: DECREASE}
이 된다.
② 상태값 반환
const todos= useSelector((state:rootState)=> state.todos)
위의 (state:rootState)
는
import {combineReducers} from 'redux';
import counter from './counter';
import todos from './todos';
const rootReducer= combineReducers({counter:counter, todos})
export default rootReducer;
// rootReducer를 호출하면 상태를 호출해준다.
// 때문에 rootReducer를 ReturnType하면은 특정함수의 리턴 타입을 추론한다.
// 음~~
//
export type rootState= ReturnType<typeof rootReducer>
rootReducer의 ReturnType이다.
③ 상태값 업데이트
const dispatch= useDispatch()
④ 구독
store.subscribe(호출할 함수);