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.
Author
Ponikar Darshan JanardanSoftware Engineer - I
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."
unknown is like a safeguard. 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);
}
}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.
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.
Thanks for reading this blog, until next time!
Subscribe to Our Newsletter
Subscribe to RSS
Press & Media Hub RSS FeedRELATED ARTICLES





