Suggestions for writing typescript code

Do’s & Don’ts by TypeScript itself

Check TypeScript list of Do’s and Don’ts

Strict configuration for type

Please turn on in the configuration the following flags:

{
    ...
   "strict": true,
   ...
}

Which will turn on flags like:

  • noImplicitThis (Enable error reporting when this is given the type any)
  • noImplicitAny (Enable error reporting for expressions and declarations with an implied any type)

Function parameters

When having a function with a lot of parameters or parameters it makes sense to change the function to take parameter as an object instead. Why?

  • It is easy to read the parameters needed
  • Objects are extendable more easily, and no need to change function parameters

Example:

const abc = (a: string, b: string, c: string) => {}

when calling the above function you write down:

const cnt = abc('a', 'b', 'c')

Which by itself it is not so readable.

Instead if you have the following function:

interface ABC {
  a: string
  b: string
  c: string
}

const abc = (abc: ABC) => {}

Calling this function would look like:

const cnt = abc({ a: 'a', b: 'b', c: 'c' })

Now you can define, check, read, and understand the idea behind the funtcion signature. Lets suppose that your decided to add also d as parameter which you would like to pass to it. Easy…

interface ABC {
  ...
  d: string | number
}

const cnt = abc({a: "a", b: "b", c: "c", d: 3});

Stay away from “bind”, as much as possible with a “French” accent

Definition of bind is something like:

bind (thisArg: any, ...anyArray: any[]) : any

This means that by using bind it’ll always return “any” and goodbye type check, you were my friend.

Better undefined than null

By they own definition the differ on that undefined means that the variable has not been declared, or has not been given a value, but null is a special value meaning “no value”. Typescript “?” operator doesn’t handle null value, and it’s recommended to use undefined for non existing values and forbid the use of null using.

Extra eslint config for blocking “any”

Add the following config to .eslintrc or .eslintrc.js

{
  ...
  "rules": {
    "@typescript-eslint/no-explicit-any": 
      "error",
    "@typescript-eslint/explicit-function-return-type": 
      "error"
  }
}

But sometime you have to skip this config for many reasons, better not!

Keep pushing forward and savor every step of your coding journey.