Отключить ошибки typescript

I am wondering if there is a way to ignore certain TypeScript errors upon compilation?

I basically have the same issues most people with large projects have around using the this keyword, and I don’t want to put all my classes methods into the constructor.

So I have got an example like so:

TypeScript Example

Which seems to create perfectly valid JS and allows me to get around the this keyword issue, however as you can see in the example the typescript compiler tells me that I cannot compile that code as the keyword this is not valid within that scope. However I don’t see why it is an error as it produces okay code.

So is there a way to tell it to ignore certain errors? I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.

== Edit ==

(Do not read unless you care about context of this question and partial rant)

Just to add some context to all this to show that I’m not just some nut-job (I am sure a lot of you will still think I am) and that I have some good reasons why I want to be able to allow these errors to go through.

Here are some previous questions I have made which highlight some major problems (imo) with TypeScript current this implementation.

Using lawnchair with Typescript

Issue with child scoping of this in Typescript

https://typescript.codeplex.com/discussions/429350 (And some comments I make down the bottom)

The underlying problem I have is that I need to guarantee that all logic is within a consistent scope, I need to be able to access things within knockout, jQuery etc and the local instance of a class. I used to do this with the var self = this; within the class declaration in JavaScript and worked great. As mentioned in some of these previous questions I cannot do that now, so the only way I can guarantee the scope is to use lambda methods, and the only way I can define one of these as a method within a class is within the constructor, and this part is HEAVILY down to personal preference, but I find it horrific that people seem to think that using that syntax is classed as a recommended pattern and not just a work around.

I know TypeScript is in alpha phase and a lot will change, and I HOPE so much that we get some nicer way to deal with this but currently I either make everything a huge mess just to get typescript working (and this is within Hundreds of files which I’m migrating over to TypeScript ) or I just make the call that I know better than the compiler in this case (VERY DANGEROUS I KNOW) so I can keep my code nice and hopefully when a better pattern comes out for handling this I can migrate it then.

Also just on a side note I know a lot of people are loving the fact that TypeScript is embracing and trying to stay as close to the new JavaScript features and known syntax as possible which is great, but typescript is NOT the next version of JavaScript so I don’t see a problem with adding some syntactic sugar to the language as people who want to use the latest and greatest official JavaScript implementation can still do so.

The TypeScript compiler is excellent at showing errors and warning when it detects something is wrong with the code. Sometimes, however, a developer may want to ignore an error on the next line AND still compile the code. Luckily, this is simple to achieve in TypeScript.

To ignore a compiler error on the next line in TypeScript, you can use the @ts-ignore rule, like so:

typescriptif (false) {
    // @ts-ignore
    console.log("unreachable code");
}

This article will go through everything on ignoring compiler errors and warnings in TypeScript and answer some common questions.

Let’s get to it 😎.

Page content

  1. How to ignore an error with @ts-ignore?
  2. How to ignore an error with @ts-expect-error?
  3. @ts-ignore vs. @ts-expect-error
  4. How to ignore all TypeScript compiler errors on a file?
  5. Final thoughts

In TypeScript, you can ignore compiler errors by adding a TypeScript directive comment above the line with the error you want to silence.

To silence TypeScript errors, multiple types of comments exist:

  • @ts-ignore
  • @ts-expect-error
  • @ts-nocheck

How to ignore an error with @ts-ignore?

The @ts-ignore comment allows suppressing an error on the next line.

Here is an example of how to use the @ts-ignore comment:

typescriptwhile(true) {
    console.log('a');
}

// @ts-ignore
console.log('b')

Read: The while loop in TypeScript

In this example, the second console.log is unreachable.

With the @ts-ignore directive comment, we silence this error.

How to ignore an error with @ts-expect-error?

The @ts-expect-error comment was introduced in TypeScript version 3.9.

It has the same behavior as the @ts-ignore comment, but with one difference.

The @ts-expect-error comment suppresses the next line error just like the @ts-ignore comment.

However, if there is no error to suppress, the compiler shows a warning that the directive is unnecessary.

Here is the same code example as above, but this time it uses a @ts-expect-error:

typescriptwhile(true) {
    console.log('a');
}

// @ts-expect-error
console.log('b')

In this example, we silence the «Unreachable code detected» error.

The behavior of the directive

In this example, the @ts-expect-error comment suppresses the error:

typescript// @ts-expect-error
console.log(20 * "Tim");

And here, the TypeScript compiler outputs an error:

typescript// @ts-expect-error
console.log(20*20);

Here, the code is valid, and the @ts-expect-error directive is unnecessary.

The TypeScript compiler outputs an «Unused ‘@ts-expect-error’ directive.» error.

@ts-ignore vs. @ts-expect-error

Since both comments suppress errors, it can be hard to choose between them.

Use @ts-expect-error when:

  • You are writing test code.
  • You expect a fix to be coming soon.
  • You have a smaller project.

Use @ts-ignore when:

  • You have a larger project.
  • You are switching between TypeScript versions.
  • You don’t know which one to choose.

How to ignore all TypeScript compiler errors on a file?

To ignore all TypeScript compiler errors of a file, add a @ts-nocheck comment at the top of the file.

Here is an example of how to accomplish it:

typescript// @ts-nocheck

if (false) {
    console.log("unreachable code");
}

This comment will silence all the errors in the file outputted by the TypeScript compiler.

Final thoughts

As you can see, ignoring TypeScript compiler errors is simple.

However, carefully consider and verify that you need it before doing so.

Usually, the TypeScript compiler shows errors for reasons, and you should only silence errors when you are 100% sure of what you are doing.

A code base should have a minimum number of TypeScript directive comments.

Since suppressing errors reduces TypeScript effectiveness, some teams implement a special Eslint rule (called ban-ts-comment) to disallow all TypeScript directive comments.

typescript ignore next line

Here are some other TypeScript tutorials for you to enjoy:

  • Exclamation mark operator in TypeScript
  • Declare class constants in TypeScript
  • Export a function in TypeScript

Tim Mouskhelichvili

written by:

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada.

I specialize in React, Node.js & TypeScript application development.

If you need help on a project, please reach out, and let’s work together.


TL;DR: to ignore a line:

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore

To disable type checking for an entire file, add the comment to the top of the file:

To disable the compiler error for a single line, add the comment before the line:

If you’re getting the lint error:

error  Do not use "@ts-ignore" because it alters compilation errors  @typescript-eslint/ban-ts-comment

Add the comment above // @ts-ignore:

// eslint-disable-next-line @typescript-eslint/ban-ts-comment



Please support this site and join our Discord!


TypeScript is a statically typed superset of JavaScript that provides optional type annotations, type inference, and other advanced language features. When writing TypeScript code, it is common to encounter type-related errors that can be difficult to resolve. In some cases, you may want to ignore these errors and proceed with compilation, either temporarily or permanently. This can be useful when you are using third-party libraries or code that does not match your type definitions, or when you are making incremental changes to a large codebase and want to avoid stopping the development process due to type errors.

To ignore all errors in a TypeScript file, you can use the // @ts-ignore comment. This comment tells TypeScript to ignore any errors that occur on the following line of code.

// @ts-ignore
const x: number = 'hello';

In the example above, TypeScript would normally throw an error because we are assigning a string to a variable that is declared as a number. However, the // @ts-ignore comment tells TypeScript to ignore this error and not throw an error.

You can also ignore errors on an entire block of code by wrapping it in a // @ts-ignore comment:

// @ts-ignore
{
  const x: number = 'hello';
  const y: string = 123;
}

In this example, both lines of code would normally throw errors, but the // @ts-ignore comment tells TypeScript to ignore them.

It’s worth noting that using // @ts-ignore should be avoided whenever possible, as it can lead to hard-to-debug issues down the line. Instead, it’s better to address the root cause of the error and fix it properly.

If you do need to use // @ts-ignore, it’s a good idea to add a comment explaining why the error is being ignored:

// @ts-ignore: This is a temporary workaround until we can fix the underlying issue
const x: number = 'hello';

In summary, to ignore all errors in a TypeScript file using // @ts-ignore, simply add the comment before the line of code that is causing the error. You can also wrap a block of code in the comment to ignore errors on multiple lines. However, it’s important to use this technique sparingly and to always address the underlying issue when possible.

Method 2: Suppress warnings in tsconfig.json

To suppress warnings in a TypeScript file, you can use the «suppressWarnings» option in the tsconfig.json file. This option allows you to ignore all the errors in a TypeScript file. Follow these steps to suppress warnings in tsconfig.json:

  1. Open the tsconfig.json file in your project.

  2. Add the «suppressWarnings» option to the «compilerOptions» object.

{
  "compilerOptions": {
    "suppressWarnings": true,
    // other options
  },
  // other configurations
}
  1. Save the file and recompile your TypeScript project.

Now, all the warnings in your TypeScript files will be suppressed. Keep in mind that this will also suppress any legitimate warnings that you might want to see.

To suppress warnings only for specific files, you can use the «exclude» option in the tsconfig.json file. This option allows you to exclude specific files or directories from the compilation process. Follow these steps to exclude specific files from the compilation process:

  1. Open the tsconfig.json file in your project.

  2. Add the «exclude» option to the «compilerOptions» object.

{
  "compilerOptions": {
    // other options
  },
  "exclude": [
    "file1.ts",
    "dir1/**/*"
  ]
}
  1. Save the file and recompile your TypeScript project.

Now, the files and directories specified in the «exclude» option will be excluded from the compilation process, and any warnings in those files will be suppressed.

Method 3: Use declare keyword

To ignore all errors in a TypeScript file, you can use the declare keyword. This keyword tells the TypeScript compiler to not emit any JavaScript code for the declared symbol, allowing you to use external libraries or variables without TypeScript type checking.

Here’s an example of how to use the declare keyword:

declare var myLibrary: any;
myLibrary.doSomething();

In this example, we’re declaring a variable called myLibrary with the type any. This tells TypeScript to not check the type of myLibrary, allowing us to call the doSomething() function without any errors.

You can also use the declare keyword with functions and classes. Here’s an example:

declare function myFunction(): void;
myFunction();

In this example, we’re declaring a function called myFunction with a return type of void. This tells TypeScript to not check the implementation of myFunction, allowing us to call it without any errors.

Finally, you can use the declare keyword with classes:

declare class MyClass {
  constructor(name: string);
  getName(): string;
}
const myInstance = new MyClass("John");
console.log(myInstance.getName());

In this example, we’re declaring a class called MyClass with a constructor that takes a name parameter and a getName() method that returns a string. This tells TypeScript to not check the implementation of MyClass, allowing us to create an instance of MyClass and call the getName() method without any errors.

That’s it! By using the declare keyword, you can ignore all errors in a TypeScript file and use external libraries or variables without any type checking.

Method 4: Use type assertions

To ignore all errors in a TypeScript file using type assertions, you can use the as keyword to tell the TypeScript compiler to treat a variable as a specific type, even if it doesn’t match the inferred type. Here’s an example:

// Ignore all errors in a TypeScript file using type assertions

// Declare a variable with an inferred type
let myNumber = 42;

// Use a type assertion to tell TypeScript that myNumber is actually a string
let myString = myNumber as unknown as string;

// Use the new variable without any TypeScript errors
console.log(myString.toUpperCase()); // Output: "42"

In this example, we declare a variable myNumber with an inferred type of number. We then use two type assertions to tell TypeScript that myNumber is actually a string. The first as unknown assertion is needed to bypass the TypeScript compiler’s type checking, while the second as string assertion tells TypeScript to treat myNumber as a string going forward.

We can then use the new variable myString without any TypeScript errors, even though it is actually a string representation of the number value 42.

It’s worth noting that using type assertions to ignore all errors in a TypeScript file should be done with caution, as it can lead to unexpected behavior and bugs. It’s generally better to address any type errors directly rather than ignoring them altogether.

I have turned on some compiler switches to report more issues in code (e.g. strict null checks). But I get tens of errors in used libraries, e.g.:

[default] xxx/node_modules/@angular/core/src/util/decorators.d.ts:11:5
    Property 'extends' of type 'Type<any> | undefined' is not assignable to string index type 'Function | any[] | Type<any>'.

Is there any way of suppressing/muting/disabling error checking in libraries (e.g. directory node_modules)?


It can’t be a duplicate of Allow implicit any only for definition files because my question is much broader. I am not asking how to disable one specific check (noImplicitAny) in libraries, but how to disable all checks in libraries. However the answer from that question applies to mine as well — "skipLibCheck": true disables all checks in libraries.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Отключить отчет об ошибках android
  • Отара овец ошибка
  • Ответственность хирурга при врачебных ошибках
  • Отключить отображение ошибок wordpress
  • От этой ситуации голова встает дыбом речевая ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии