We can use two options to define types in TypeScript:
-
explicit typing - declares types directly in the code
// exsplisit as string let personOne: string = 'Mary'; // exsplisit as number let personOneAge: number = 25; // exsplisit as string const personTwo: string = 'Bob'; // exsplisit as number const personTwoAge: number = 22;
-
implicit typing - TypeScript inferences types automatically with the context.
// implicit as string let personOne = 'Mary'; // implicit as number let personOneAge = 25; // implicit as "Bob", since we can't re-assign consts const personTwo = 'Bob'; // implicit as 22, since we can't re-assign consts const personTwoAge = 22;
In most cases, the Type Inferences works fine, but there are some cases where we need to use explisity typing.
The general idea - try to avoid implicity inferred any
as much as possible. Some basic examples:
// inferred as any
let name;
name = 'Bob';
// inferred as string
let name: string;
name = 'Bob';
// inferred as (num: any) => any
const count = (num) => num + 2;
// inferred as (num: number) => number
const count = (num: number): number => num + 2;
Also, external operations and data structures are good signs to use explicit typing.
GOOD PRACTICE: You can check some of such cases automatically. Just add at least these compiler flags in your tsconfig.json
:
--noImplicitAny
- to avoid introducing anys inside your codebase when a type could be specified.--noImplicitThis
- to raise errors when ‘this’ would be any.