TypeScript is used to reduce errors in code. However, many developers “turn off” TypeScript type checking for a single line with @ts-ignore. This is dangerous because it masks compilation errors.
If you are using TypeScript and TypeScript-ESLint in a team setting, you can ban TypeScript comments by adding the
@typescript-eslint/ban-ts-comment rule to your
eslintrc.json file. Developers will no longer be able to ignore TypeScript errors thrown by the compiler.
@TypeScript-ESLint Ban-TS-Rule Code Example
In this example I am using the Material UI Select component. The event type is supposed to be
event: SelectChangeEvent<string>. However, that requires knowing about and importing SelectChangeEvent.
As a developer, if I am unfamiliar with MUI I may be tempted to skip the typing of the event parameter and instead use
ban-ts-rule enabled and set to “error” I will not be able to take this shortcut. The compiler will throw an error until proper typing is added.
How to Disable TypeScript-ESLint/Ban-TS-Rule
@typescript-eslint/ban-ts-comment is not a default rule in @typescript-eslint and must be added. This likely is a team or tech lead decision.
It may be difficult to enforce when using third-party libraries. In my experience, even the best 3p libraries like MUI sometimes have type bugs in them, especially when a version upgrade is released.
There are two ways around an absolute ban-ts-rule:
- Set the rule to “warn” in
If I set
"@typescript-eslint/ban-ts-comment": "warn" in my
eslintrc.json, then the compiler doesn’t block @ts-ignore. Instead it adds warnings that will alert the dev or team about the issue without blocking development.
eslint-disable-next-line can still be used to allow
I suggest setting the rule to “warn” is a better solution for delaying the type fix because it lets the code stay cleaner.
A final option for disabling the rule is to override it for a folder or file path using .eslintrc.json overrides.
Here’s how to enable a max length rule to keep lines from getting too long.
What Happened to Ban-TS-Ignore?
The TSLint rule
ban-ts-ignore is deprecated and replaced with ban-ts-comment, which has more customization and bans more comment types.
You can read more in this github thread.
By default, this rule disables ts-ignore, ts-expect-error, and ts-no-check. Read the docs to configure the rule to only disable a subset of these comments.