How to define types in TypeScript

· Category: TypeScript

Short answer

Use type annotations after a colon to declare the type of a variable, function parameter, or return value.

Steps

  1. Variable types: let count: number = 0;
  2. Function parameters: function add(a: number, b: number) { ... }
  3. Return types: function add(a: number, b: number): number { ... }
  4. Object types: const user: { name: string; age: number } = { name: 'Ada', age: 30 };
  5. Array types: let items: string[] = ['a', 'b'];

Tips

  • Type inference means you often do not need explicit annotations when TypeScript can deduce the type from the initial value.
  • Use readonly for arrays and properties that should not be reassigned.

Common issues

  • Implicit any appears when TypeScript cannot infer a type and strict mode is off. Enable noImplicitAny to catch these.
  • Over-annotating simple expressions adds noise without value; let inference do the work.