TYPE- any in ts - DAY3 OF 100DAYSOFCODE
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
Any type in typescript
in the previous article, if you remember the last moment, if we don't declare and initialize value in the same line then it will return any type.
I hope you also remember, that we can give type by ourselves ( type annotation) or typescript will auto assume type ( inference ). so any type is also possible with both. either we explicitly mention type to any variable or if typescript doesn't understand type then it will inference any type. let's understand from the below example.
here, we are set to type to isExists to any. same as we set type age to number. now let's understand for inference. if you are still confused about inference then kindly check my last blog.
if you check age2 typescript is set automatically to type to number but in isProductExists, it is set to any. why!!
because JSON.parse() function return type depends on given params like it returns boolean, number, object anything. so here typescript is not aware of the return type. so if typescript doesn't understand the exact output type then it will give back any type.
We can understand any type is the same as plain javascript. you can also change the value to a string, a number, or any other type which will not give any error also while compiling ts file to js.
did you notice? we are assigning random parmas, still, it does not give a red underline. if we set it to boolean then it will definitely give a red underline because we do not use like objects.
in short, you should avoid any types in all scenarios otherwise it makes no sense to use typescript. typescript is used to understand the type of data. so let's understand how to avoid this scenario.
领英推荐
Fix any type:
Here isMeetExists has any type because we are assigning value to a later stage. you also notice that we are assigning "hehehe" in the last line and ts not gives red underline.
in this type of scenario always gives types when you declare you also declare type also like,
Now typescript gives an error that "Property 'hehehe' does not exist on type 'boolean'".
let age = JSON.parse('24')
age = "twenty four" // will not give error
let age1: number JSON.parse('24')
age1 ="twenty four" // will gives error