Jan 2, 2023

TypeScript: Any, Unknown and Never

As part of this blog, we will explore special type annotations. We will be looking at some unique TypeScript annotations in addition to how type annotations work.
Ponikar Darshan Janardan
Ponikar Darshan JanardanSoftware Engineer - I
lines

1. Any

anyis like an escape hatch; it can be used when you are not sure about a type. When you use any type annotation, you are just saying to TypeScript:

"Hey TypeScript, I don't have any idea about this type. So don't bother to check this type."

You should avoid any annotation for as long as possible. Using any is similar to using javascript without type safety.

Following is an example of any :

2. Unknown

When you use unknown type annotation, you are just saying to TypeScript:

"Hey, TypeScript, I'm not sure about this type, but please remind me to check it during runtime."

unknown is like a safeguard. By checking types at runtime, we can ensure that we are not writing any buggy code.

3. Never

never is useful when you are working with type manipulation. never simply means that the type doesn't exist anymore.

It is used to filter types and perform error handling. Let's assume we are writing a function, and we are sure that this function will throw an error. Since this function is not returning anything and our program will likely be stopped, we can assign never as the return type.

This example might not make sense to you now, but there are plenty of situations in which never can be really useful.

You are now aware of the specific type annotations. This will aid in understanding complex TypeScript ideas such as utility types, type of types, condition types, and so on. Keep an eye out for future blogs.

Thanks for reading this blog, until next time!

Hire our Development experts.