I'm working on a create-react-app with TypeScript and it auto-generates a tsconfig in my frontend folder with "include": "/src"
every time I run the app, even if I delete the file or change it.
Is there a way to disable type checking in a TS cra (without ejecting)?
CRA uses Babel compiler
Babel is third part compiler for Flow, JSX and TypeScript with combining it. Babel does not implement type checking, CRA uses some methods from TypeScript Compiler and some of them from TSLint. So Babel can compile code even if there is a Type Error because Babel doesn't see it. Add this to the environment:
TSC_COMPILE_ON_ERROR=true
For more detail see CRA documentation
One file disabling
Use // @ts-nocheck
or /* tslint:disable */
(depending on version of CRA) at the start of the file.
any
typeAlso, In TypeScript, types may be optional when defined that way. So you can't use it if you use in tsconfig.json
{
"compilerOptions": {
///...
"strict": false
}
}
Since it seems like the biggest pain you are having is finding type definitions for external libraries, you can create an ambient definition for any variable you don't want to type checking for:
declare var variableName: any;
// better in .d.ts files
For example, for jQuery it would be declare var $: any;
. Then you could do: $("#test").myNonExistentFunction();
if you wanted.
Alternatively, when using es2015 modules the following code could be done to allow the library to be imported:
declare module "jquery" {
var _temp: any;
export = _temp;
}
Shorthand ambient module declarations (TS 2.0+)
In TS 2.0+, a better way to disable type checking for imports is to create a .d.ts
file in your project and define shorthand ambient module declarations:
declare module "jquery";
// or use a wildcard
declare module "express-*"; // or use "*" to allow everything
This will allow you to use those imports freely without type checking:
import $ from "jquery";
$.something(); // ok at compile time, but will be an error at runtime
That said, the best path to take in this scenario is in a .d.ts
file in your project to gradually define the interface of the library you're depending on based on what you use.
ts-ignore comments (TS 2.6+)
It's possible to disable any TypeScript error by using // @ts-ignore
comments in TypeScript 2.6+. For example:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
@ts-expect-error
comment (TS 3.9)
Expecting error is better, safer and more stable than ignore. Note that it works for next code line which means you can use comments between code and @ts-expect-error
.
// @ts-expect-error
/* I will override error */
//
var num: string = 3;
No difference? Try to use this rules:
Pick ts-expect-error
if:
Pick ts-ignore
if:
Sources: https://stackoverflow.com/a/31089657/14724418, https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html