简体   繁体   中英

Typescript how to ignore 'types' can only be used in a .ts file error

I have large project (around 700+ files) written in JavaScript with flow. I want to migrate it to TypeScript. My goal is to keep current files intact and I want to write new functions in TypeScript. My problem is it throws me an error 'types' can only be used in a.ts file . Is it possible to suppress this error? I definitely don't want to rewrite every single file in solution.

My IDE is visual studio enterprise 2019

tsconfig

{
"compilerOptions": {
    "target": "es5",
    "lib": [
        "dom",
        "dom.iterable",
        "esnext"
    ],
    "allowJs": true,
    "checkJs": false,
    "skipLibCheck": true,
    "noEmitOnError": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
},
"include": [
    "src"
]}

You can't use types in a JavaScript file, typescript will not perform type erasure on js files so you would end up with invalid js even if you suppress the error.

If you want to migrate change the extension to ts , your compiler settings are permissive enough that most js will be valid ts. You can then invoke the compiler on your new ts files to get the corresponding js (Since most of it will not yet have types, the output should be the same as the input and the same as your original js files)

If you want to keep js files, you could use JSDoc comments instead of type annotations. See example here . This will give you most of the benefits of explicit type annotations, just in a more verbose syntax. Later when you want to move to ts, there is a quick fix to move jsdoc types to ts annotations (at least there is one in VSCode I expect it is also surfaced in VS).

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