Typescript is becoming more and more popular (shown as “Most Adopted Technology” of 2020 by State of JS. This post will list some good practices that you can use to get the best out of TypeScript.
- Strict mode
Configure TypeScript in strict mode in order to always benefit from the type checking.
In tsconfig.json :
{ "forceConsitentCasingInFileNames": true, "noImplicitReturns": true, "strict": true, "noUnusedLocals": true }
- Never use any
There is a possibility to add options in tsconfig.json to totally forbid it.
- Avoid using ‘bind’
bind always returns ‘any’ and cannot check the type of the parameters, so it’s not very safe to use it.
Instead of:
const cb = this.updateOffset.bind(offset);
You’d rather write something like this:
const cb = (offset: string) => this.updateOffset(offset);
- Generics
Generics (documentation) are useful when we want to define an interface with a variable typed property.
We could for instance have these two interfaces:
interface UsersResponse { success: boolean; msg: string; data: User[]; } interface CarsResponse { success: boolean; msg: string; data: Car[]; }
We have to repeat the same properties, and only ‘data’ has a different type. We could use a generic and have only one interface:
interface Response<T> { success: boolean; msg: string; data: T; }
We can use it like this:
const response: Response<User[]>;
- Type function return
Always type the functions return.
- Use private, public, protected
Try to use ‘private’ most of the time.
- Use Utility Types (Partial, Pick, Readonly…)
Some examples for this interface:
interface User { firstName: string; lastName: string; email: string; phone: number; birthday: number; }
- Partial<User> : all properties are optional
- Pick<User, ‘firstName’ | ‘lastName’> : only firstName and lastName are defined
- Readonly<User> : explicitly say that the variable is readonly
- Configure VS code & ESlint
VS Code & ESLint configuration explained here.
- Don’t prefix interfaces by I (deprecated)
- Function parameters
Instead of:
function compute(x: number, y: number, z: number) { ... } compute(2, 3, 4);
We can write something like this in order to ease the reading when we call the function:
function compute(options: {x: number; y: number; z: number}) { ... } compute({ x: 2, y: 3, z: 4 });