Typescript’s directives to ignore compiler time errors

Yuri Fenyuk
3 min readOct 5, 2021
TS logo

Typescript does a good job with type checking and this aspect of language is constantly improving with every next release. No doubt it is one of the most valuable treasures for every developer. However, sometimes (more about reasons below) I would like to have the ability to insist on my code and let it compile and run.

The common solution is to cast the variable to any or through unknown to the more specific type, like as unknown as string before passing a variable into function’s string parameter. Although this workaround is the quickest one it is smelling. In every similar case, I swear to stop doing it… and I can not.

So, I have simple sum function with type checking with parameters type assertion and I am trying to call it with crazy arguments:

Sure thing, code will neither compile or execute:

Compile error

It can be easily made compiled but asserted during runtime:

Runtime error

The very same effect can be reached with @ts-ignore compiler directive:

use @ts-ignore to compile

It is worth to mention that @ts-ignore scope is only one line of code below and such behavior is by intention. In case a block of lines or whole file needs to skip compile checking, there is @ts-nocheck directive, although it slightly different.

Since Typescript v3.9, which was released last year, @ts-expect-error directive is available. It has next line effect as well and let this line be compiled similar to @ts-ignore. The difference is that the newer directive will throw compile time exception if the compiler found no problem in the below line.

runtime assert

Let’s put correct numbers as function parameters:

And now code even can not be complied, since no promised with directive error detected:

So, when use any of described approaches to live with code which is failing to be complied?

Most desirable answer — never use it and keep your code nice and clean. but all of us live in reality with non ideal development processes and bad smelling code.

  • if you intentilly writing code which suppose to fail (probably, unit testing it), putting @ts-expect-error might be the option
  • if you have/joined fairly large project where the source error is not clear to the owner of failing code is unknown, ignoring might be a temporary solution
  • if you do Typescript version upgrade and code which worked OK is not longer complied, ignore could be temporary option to let you finish migration
  • if you need a quick workaround and promise yourself to get it properly fixed later

All code and outputs are available on my github as well.

--

--