DEV Community

Alaa Courdova
Alaa Courdova

Posted on

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.

Top comments (0)