TypeScript: Any, Unknown and Never

TypeScript: Any, Unknown and Never

In this blog, we will learn about special type annotations.

Table of contents

In this blog, we'll explore some unique TypeScript annotations. We will look at the functioning of type annotations and learn a bit about them.

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 :

let a:any = "Hello world"

// We lost type safety!
a = 123;

const myFunctions = (args: 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."

By checking types at runtime, we can ensure that we are not writing any buggy code.

const myFun = (args: unknown) => {

   // this will give you an error since the type is unknown.
   const length = args.length;

  // we are checking if args is having string type or not.
    if(typeof args === "string") {
           return args.slice(0,2);
    }
}

unknown is like a safeguard. Even though we are not aware of type. We are making sure that we are writing type-safe codes.

3. never

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

Never 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.

const crashCode = () :never => {
     throw new Error("Boom...");
}

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.

Thank you for taking the time to read this blog.