TS&React

김수민·2023년 2월 20일
0

TypeScript

목록 보기
5/8
  1. cmd에서 npx create-react-app 폴더명 --template typescript하여 폴더 생성
  2. 폴더의 터미널에서 npm install 할 시 npm install @types/설치대상명와 같이 @types/를 앞에 붙여 install 한다.

타입지정

props 전달 시


하위 컴포넌트로 props를 전달할 시

해당 컴포넌트에서 타입을 지정해주어야한다.

function TodoItem({todo}:{todo:Todo}){
}

props 타입을 위와 같이 지정하는 경우는
props가 객체이기 때문에, 해당 객체의 todo에 타입을 지정한 것이다.

함수의 event의 타입 지정


React.해당하는이벤트<해당하는위치> 로 타입을 지정해준다.

dispatch 타입 지정

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>

제네릭

children 타입 지정

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 지정시

style의 타입은 React.CSSProperties이다.

상태관리

State 작성 시

작성하면, 자동적으로 타입이 지정된다.
타입을 지정하고 싶을 시 아래와 같이 지정한다.

const [] =useState<number>(0)

Reducer 사용시

useReducer(reducer,state)

Redux 사용시

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 >

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(호출할 함수);
profile
sumin0gig

0개의 댓글