React新手遇TypeScript报错:找不到react-cards声明文件
Hey there! I totally get how frustrating this TypeScript error can be when you're just starting out with React. Let's break down what's happening and fix it step by step.
Why This Error Happens
The error pops up because:
- The
react-cardspackage doesn't include built-in TypeScript type declarations. - There's no official
@types/react-cardspackage available on npm (which is why installing it didn't help). - TypeScript needs type info to understand what's in the module, so it defaults to treating it as
anyand throws this warning/error.
Solution 1: Create a Custom Declaration File
This is the cleanest long-term fix if you want to keep using react-cards:
- In your project, create a
typesfolder (you can put it in the root or inside yoursrcdirectory). - Inside that folder, make a new file named
react-cards.d.ts. - Paste this line into the file:
declare module 'react-cards'; - Open your
tsconfig.jsonfile and make sure theincludearray includes your types folder. For example:"include": [ "src/**/*", "types/**/*" ]
This tells TypeScript to recognize the module and stops the error. If you want more detailed types later, you can expand this declaration file with the component's props and methods as you learn more about the library.
Solution 2: Skip Type Checking Temporarily
If you just need to get up and running quickly, you can add a comment to ignore the error for that import:
// @ts-ignore import Card from 'react-cards';
Note: This is a quick fix, not a permanent solution—it disables TypeScript's type checking for this line, so you won't get helpful hints or error checks for the Card component.
Bonus: Consider a TypeScript-Friendly Alternative
If you want to avoid these type issues entirely, you might switch to a component library that supports TypeScript out of the box. Some popular options are:
- Material UI's
Cardcomponent (part of@mui/material) - React Bootstrap's
Cardcomponent - Chakra UI's
Cardcomponent
All of these have official type declarations, so you won't run into this kind of error.
Hope one of these solutions works for you! Happy coding!
内容的提问来源于stack exchange,提问作者Ryukote

