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
- Variable types:
let count: number = 0; - Function parameters:
function add(a: number, b: number) { ... } - Return types:
function add(a: number, b: number): number { ... } - Object types:
const user: { name: string; age: number } = { name: 'Ada', age: 30 }; - 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
readonlyfor arrays and properties that should not be reassigned.
Common issues
- Implicit
anyappears when TypeScript cannot infer a type and strict mode is off. EnablenoImplicitAnyto catch these. - Over-annotating simple expressions adds noise without value; let inference do the work.