简体   繁体   中英

Do I need to install @types/react to work with React in a TypeScript project?

I'm converting my project from JavaScript to TypeScript.

This is my current package.json dependencies:

  "devDependencies": {
    "@babel/cli": "^7.10.5",
    "@babel/core": "^7.10.5",
    "@babel/node": "^7.10.5",
    "@babel/preset-env": "^7.10.4",
    "@babel/preset-react": "^7.10.4",
    "@babel/preset-typescript": "^7.10.4",
    "babel-loader": "^8.1.0",
    "babel-plugin-module-resolver": "^4.0.0",
    "babel-plugin-styled-components": "^1.10.7",
    "clean-webpack-plugin": "^3.0.0",
    "dotenv-webpack": "^2.0.0",
    "file-loader": "^6.0.0",
    "html-webpack-plugin": "^4.3.0",
    "ngrok": "^3.2.7",
    "rimraf": "^3.0.2",
    "webpack": "^4.44.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "@hot-loader/react-dom": "^16.13.0",
    "core-js": "^3.6.5",
    "firebase": "^7.17.1",
    "md5": "^2.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-helmet": "^6.1.0",
    "react-hot-loader": "^4.12.21",
    "react-redux": "^7.2.1",
    "react-router-dom": "^5.2.0",
    "redux": "^4.0.5",
    "regenerator-runtime": "^0.13.7",
    "styled-components": "^5.1.1",
    "uuid-v4": "^0.1.0"
  }
}

I've imported react and react-dom and I'm getting the following warnings:

Could not find a declaration file for module 'react'. Try npm install @types/react if it exists or add a new declaration (.d.ts) file containing `declare module

The same for react-dom

Could not find a declaration file for module 'react-dom'. Try npm install @types/react-dom if it exists or add a new declaration (.d.ts) file containing `declare module

Infact, all the libraries I've imported so far are giving me the same warning:

index.tsx

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router} from 'react-router-dom';
import { Provider } from 'react-redux';

Do I need to install those @types/react to work with React with TypeScript? Will I also need to install the @types/package for every library that I import? How does that work?

Yes. Or, well, to elaborate, to use a JS library with TypeScript, you'll need to

  • use a library that ships TS types itself (many do, these days), or
  • install the related @types/ package (which stem from DefinitelyTyped ); tooting my own horn here, I wrote a package called autotypes that can help , or
  • write a .d.ts file for the library in your project's working cop, as below:
declare module 'some-library' {
  export const doInterestingThings(): void;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM