useEffect(() => {
    const getMeals = async () => {
      setIsLoading(true);
      try {
        const response = await fetchMeals();
        setMeals(response);
      } catch (error) {
        
          setError({ message: error.message });
        
      }
      setIsLoading(false);
    };
    getMeals();
  }, []);

과 같은 코드를 짜고 있는데 

setError 부분에서 
'error'은(는) 'unknown' 형식입니다.ts(18046)

에러가 났었다

난 분명 fetchMeals 함수에서 에러가 났을 경우 throw new Error를 통해 에러 객체를 보내줬었는데

왜 계속 unknown이라고 하는거지 하고 헤맸었다

 

ai에게 물어보니 이유가 다음과 같다고 한다

 

1. TypeScript는 기본적으로 catch 절의 매개변수를 unknown 타입으로 취급합니다. 이는 TypeScript 2.0부터 도입된 안전한 에러 처리를 위한 기능입니다.
2. 비동기 함수에서 발생하는 오류는 다양한 원인(네트워크 오류, 파싱 오류 등)으로 인해 발생할 수 있으며, 이들이 모두 Error 인스턴스라고 보장할 수 없기 때문입니다.

 

이렇기 때문에 

useEffect(() => {
    const getMeals = async () => {
      setIsLoading(true);
      try {
        const response = await fetchMeals();
        setMeals(response);
      } catch (error) {
        if (error instanceof Error) {
          setError({ message: error.message });
        }
      }
      setIsLoading(false);
    };
    getMeals();
  }, []);

이렇게 타입 가드를 넣어주면 된다

기본 프로젝트를 typsscript 프로젝트로 바꾸기 위해 GPT에게 물어보았습니다

 

 

이미 프로젝트가 설정되어 있다면, TypeScript, ESLint, Prettier를 추가하는 방법을 설명할게요.

1. TypeScript 설정

먼저, TypeScript와 관련된 패키지를 설치해야 합니다.

npm install --save-dev typescript @types/react @types/react-dom

다음으로, TypeScript 설정 파일을 생성합니다.

npx tsc --init

이 명령어는 기본 tsconfig.json 파일을 생성합니다. 생성된 파일을 열어 프로젝트에 맞게 수정할 수 있습니다. 주요 설정은 다음과 같습니다:

{
  "compilerOptions": {
    "jsx": "react-jsx",
  },
  "include": ["src/**/*"]
}

// vite + typescript를 쓰고 .env를 쓸 것이면 아래와 같이 업데이트를 해주면 좋다
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "bundler"
  },
  "include": ["src/**/*"]
}

2. ESLint 설정

ESLint 설정 파일 .eslintrc.js를 생성하고 필요한 패키지를 설치합니다

npx eslint --init

설정 파일에서 TypeScript와 React 관련 규칙을 추가해야 합니다. .eslintrc.js 파일을 다음과 같이 설정할 수 있습니다:
이 설정을 할때 지금 타입스크립트를 사용중이냐라는 질문을 하는데 바로 타입스크립트로 바꿀거면 yes를 누르도록 하자

module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended'
  ],
  parserOptions: {
    ecmaVersion: 'ESNext',
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    // 여기에 프로젝트에 맞는 규칙을 추가하세요.
  },
  settings: {
    react: {
      version: 'detect'
    }
  }
};

3. Prettier 설정

Prettier를 설치하고 설정합니다.

npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier

프로젝트 루트에 .prettierrc 파일을 생성합니다.

{
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "endOfLine": "auto"
}

ESLint와의 통합을 위해 .eslintrc.js에 다음과 같은 설정을 추가합니다:

module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended' // Prettier와 통합
  ],
};

4. 스크립트 업데이트

package.json 파일에 ESLint와 Prettier를 실행할 수 있는 스크립트를 추가합니다.

{
  "scripts": {
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
    "format": "prettier --write ."
  }
}

이제 npm run lint로 코드 린팅을, npm run format으로 코드를 포맷팅할 수 있습니다.

5. src/custom.d.ts 선언

declare module '*.jpg';
declare module '*.png';
declare module '*.jpeg';
declare module '*.gif';


declare module '*.module.css' {
  const classes: { [key: string]: string };
  export default classes;
}

 

이미지 파일의 에러를 막아준다

6. TypeScript로 파일 변환

src 폴더의 .js 또는 .jsx 파일들을 .ts 또는 .tsx로 변환합니다. 이후, TypeScript의 타입 체크 기능을 활용해 코드를 개선해 나가면 됩니다.

 

7. src/types/globla.d.ts 생성

이곳에 global type들을 담아주면 된다

8. src/vite-env.d.ts

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_APP_TITLE: string;
  // 다른 환경 변수들에 대한 타입 정의...
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

이렇게 설정해 주어야 typescript + vite를 사용할 때 에러가 나오지 않는다

+ Recent posts