TypeScript’s any vs unknown vs never: When and How to Use Them
Making Informed Decisions for Safe and Precise Typing in TypeScript
any
and unknown
are the two escape ways that we use when we aren’t sure about what will be the type of value, whereas never
is used when we are out of all data types, we are left with no values.
Today we’ll be seeing the usage of them and understand them better.
any
when used, it simply turn off the type checker. We can assign anything to the variable which is marked any
type.
Drawback:
1. we can even call a method on undefined, and typescript won’t give us any error.
Let’s see how unknown
solves this problem.
unknown
When we start our journey in typescript then it is very hard to specify types for everything we use and sometimes google search also fails or takes time.
In such cases with precaution, we can use unknown
.
What does unknown
do?
You can think of unknown
as any on steroids
.
when you make any variable of type unknwon
, you can assign anything to it just like any
, but when you try to access something from it, typescript will give you an error.
Stating that whatever you are trying to access for a unkwnown
variable type might not exists.
unknwon
enforces you to add a check, before using anything from a variable of unknown
type.
Now by seeing the error, typescript is expecting us to enforce type/value check before consuming the unknown
type.
By Replacing any
with unknown
, the benefit we get is the error
that typescript throws.
Now if we want to perform any operation on unknown
type then we have to add additional checks.
and for functions, the checks are more stricter
unknown
, ensures that we are using correct operation of data type.
never
never
can be considered as opposite to any
type.
any
says give me anything, and never
says give me nothing.
never
is used when we have exhausted all possible value and we don’t have anything to assign.
Let’s see some cases where we don’t have anything to assign.
- in if else block
Here in else
block, if we get anything other than string or number then error will be thrown.
It also handles if some one changes the function signature to accept object
, and if there isn’t a if to handle object
type, we will be able to see the error in compile time itself.
2. in switch
3. in a function which throw error
we know what this function will never reach to its execution and won’t return anything. And that’s a perfect case to assign never
as a return type.
4. never
is often used with conditionals
I hope this article made you learn something new.
In case you have any doubt or want to understand any concept related to web development, book as session with me on topmate. https://topmate.io/frontendmaster