使用react-native init创建项目后VSCode报错:'type aliases'仅可用于.ts文件
Hey there, let's work through this annoying error you're seeing after initializing a React Native project. That message pops up for a few common reasons, and we can knock it out in a straightforward way:
Why this happens
Most often, this error means you've got TypeScript-specific syntax (like type or interface declarations) in a .js file. VSCode doesn't expect TS syntax in plain JavaScript files by default, so it throws this warning. Sometimes the default React Native template might even have a tiny mix-up here, but no worries—easy fixes ahead.
Step 1: Check your file's syntax
First, open up the .js file triggering the error. Look for code that looks like this:
type User = { name: string; age: number; };
If you spot that, you've got two solid options:
- Switch to TypeScript: Rename the file to
.ts(or.tsxif it's a React component). VSCode will immediately recognize it as a TS file, and the error will vanish. This is the cleanest pick if you plan to use TypeScript long-term. - Stick with JavaScript: Replace the TS type alias with JSDoc comments, which are fully JS-friendly:
/** * @typedef {Object} User * @property {string} name * @property {number} age */
Step 2: Tweak your project's JS/TS config
If you're working with a mix of JS and TS files, or you want VSCode to allow TS-like syntax in JS files, create or update a jsconfig.json file in your project root with these settings:
{ "compilerOptions": { "allowJs": true, "checkJs": true, "noEmit": true }, "exclude": [ "node_modules", "babel.config.js", "metro.config.js", "jest.config.js" ] }
This tells VSCode to enable TypeScript checks for JavaScript files without generating compiled output files.
Step 3: Restart the TypeScript server in VSCode
Sometimes config changes don't kick in right away. Fix that quickly:
- Hit
Ctrl+Shift+P(Windows/Linux) orCmd+Shift+P(Mac) to open the command panel - Search for and run
TypeScript: Restart TS Server
Step 4: Double-check default template files
Occasionally, the default React Native init template might include TS syntax in a .js file by accident. Scan through generated files like App.js to see if there's a stray type or interface hiding there. If so, fix it using Step 1's methods.
Pro tip for future projects
If you know you want to use TypeScript from the start, initialize your project with the TS template directly:
react-native init MyProject --template react-native-template-typescript
This sets up all the correct configs out of the box, so you won't run into this issue at all.
内容的提问来源于stack exchange,提问作者thana

