DEV Community

Alaa Courdova
Alaa Courdova

Posted on

2 1

what to do when you can't typedef 'any' .. ?

It's best practices to not let your code with no type :

let address;
let name;

this code above doesn't say much about how the address will be presented !

will it be one line:-

"address": "22 Rue du Grenier Saint-Lazare\n75003 Paris\nFrance"
Enter fullscreen mode Exit fullscreen mode

or

series of structured attributes :

{
  "address": {
    "street": "22 Rue du Grenier Saint-Lazare",
    "postalCode": "75003",
    "city": "Paris",
    "countryCode": "FRA",
    "country": "France",
    "text": "22 Rue du Grenier Saint-Lazare\n75003 Paris\nFrance"
  }
}
Enter fullscreen mode Exit fullscreen mode

that's why it is important to add type to your code , but on other hand 'any' is a type too ??

is it ok ?

No!.. as 'any' type on typescript is not doing us any favor it also doesn't provide much knowledge about the structure that we sending to a function ... unit test ... API call .. etc.

so to prevent this happening, I add a tslint rule on the project file tslint.json:

"no-any": [true, {"ignore-rest-args": true}],

this rule alarm developer to 'any' type used it is very cool ..

Note
If "ignore-rest-args": true is provided rest arguments will be ignored.
this rule will effect the all file , so if you touched an old file while adding this lint rule you need to add types to all variables with 'any' type

Passes

let foo: object;
Enter fullscreen mode Exit fullscreen mode

Fails

let foo: any;
Enter fullscreen mode Exit fullscreen mode

for more details :

I came cross challenging situations when a function takes an attribute , but due to 'any' type or no-type at all the attribute was once string the other call number !! it is confusing

so what to do Now !!

I found that we can use 'union type' it is like you can add both types to a single variable

value: string | number;
Enter fullscreen mode Exit fullscreen mode

that's do the trick ! and you can add as much type as you want using '|' pipe sign.

I am not sure if it is a good practice , but don't over use it :D

Hope it was useful.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay