javascript -> typescript로 변환하기

nevermind·2023년 1월 16일
0

typescript

목록 보기
9/12

TodoList Javascript버전을 Typescript로 바꾸어보기

  • npm i typescript
  • npm i --save-dev @types/styled-components
  • npm install react-router-dom @types/react-router-dom
  • tsconfig.json 생성

  • js, jsx -> ts, tsx로 변환
    -> 이렇게 되면 빨간줄들이 다 뜨게 된다! 타입지정을 통해 하나씩 수행해줘야한다.
    -> 나같은 경우에는 contextAPI로 진행을 하였는데 값들을 타입지정해줘야했었다. (익숙해지길..)
    -> 또한 add, delete, update 등도 타입을 지정해줘야했다

//TodoContext.tsx
import * as React from 'react';
import { createContext, useContext, useState } from 'react';
import { State, UserContextType, defaultValue } from './types';

//기본값 null
const TodoContext = createContext<UserContextType | null>(null);

//children 또한 타입지정, props해주는 모든 것 타입 지정해줘야한다
export const TodoProvider = ({ children }: { children: React.ReactNode }) => {
  const [todoList, setTodoList] = useState<State[]>([defaultValue])

  const addTodoItem = (newItem: State) => {
    setTodoList([...todoList, newItem])
  }

  const delTodoItem = (id: string) => {
    const newList = todoList.filter((data, index) => data.id !== id)
    setTodoList(newList)
  }
  const updateTodoItem = (item: State) => {
    const changeData = todoList.map((data, idx) => item.id === data.id ? { id: item.id, todo: item.todo, isCompleted: item.isCompleted, userId: item.userId } : data)
    setTodoList(changeData)
  }
  let todoListLength = todoList.length

  const contextValue: UserContextType = {
    todoList,
    setTodoList,
    addTodoItem,
    delTodoItem,
    updateTodoItem,
    todoListLength
  }
  return <TodoContext.Provider value={contextValue}>
    {children}
  </TodoContext.Provider>
}


export const useTodoContext = () => useContext(TodoContext);
//types.ts 타입들만 모아놓음

import { Dispatch } from "react"

export type State = {
    id: string,
    todo: string,
    isCompleted: boolean,
    userId: number,
}
export type TodosState = State[];

export const defaultValue: State = {
    id: '',
    todo: '',
    isCompleted: false,
    userId: 0,
}

export type UserContextType = {
    todoList: State[],
    setTodoList: Dispatch<React.SetStateAction<State[]>>,
    addTodoItem: (newItem: State) => void,
    delTodoItem: (id: string) => void,
    updateTodoItem: (item: State) => void,
    todoListLength: number | undefined
}

error

  • 에러가 많이 발생했었다.

  • import React from 'react'; -> import * as React from 'react';

  • axios도 타입을 줘야한다.. AxiosInstance

import axios,{AxiosInstance} from "axios";

export const api:AxiosInstance = axios.create({
  baseURL: baseURL
})
  • contextAPI가 시간이 제일 많이 걸렸고 위와 같이 해결했다

  • 아래 코드에서 에러가 발생했다

const root = ReactDOM.createRoot(document.getElementById('root'));

//에러메시지
Argument of type 'HTMLElement | null' is not assignable 
to parameter of type 'Element'. 
Type 'null' is not assignable to type 'Element'.ts(2345) in VScode.

// 해결법 (조금 더 찾아봐야할듯)
1.ReactDOM.createRoot(document.getElementById('root')) as HTMLElement; 
2. ReactDOM.createRoot(document.getElementById('root')!);
느낌표를 써주는 방법을 통해 null을 나타낼 수 있다
변환 완료했으니, react-query를 공식문서보고 공부해보자!

출처: https://stackoverflow.com/questions/63520680/argument-of-type-htmlelement-null-is-not-assignable-to-parameter-of-type-el
https://velog.io/@gptn719/TypeScript-in-import-as-React-from-react-import-%EA%B5%AC%EB%AC%B8%EC%9D%B4-%EB%B0%94%EB%80%8C%EB%8A%94-%EC%9D%B4%EC%9C%A0

profile
winwin

0개의 댓글