JS Learning

Type Annotations

TypeScript Type SystemSection 1 of 4beginner

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Type annotations are like labels you put on your variables and functions to tell TypeScript what kind of data they should contain. It's like labeling boxes when moving - you know exactly what's inside!

What are Type Annotations? Type annotations use a colon (:) followed by the type name. They're your way of telling TypeScript "this variable should only hold this type of data."

Basic Variable Types:

  • string:for text like "Hello" or 'World'
  • number:for any number (integers or decimals)
  • boolean:for true or false values
  • array:for lists of items
  • object:for complex data structures

Why Use Type Annotations? 1. Prevent mistakes: Can't accidentally put a number where text should go 2. Better autocomplete: Your editor knows exactly what you're working with 3. Self-documenting: Anyone reading your code knows what data to expect 4. Refactoring safety: Change types and see all affected code immediately

Function Type Annotations:

  • Parameters:Tell TypeScript what types of arguments a function accepts
  • Return types:Specify what type of value a function gives back
  • Optional parameters:Use ? to make parameters optional
  • Default values:Provide fallback values for parameters

Common Patterns:

  • Union types:let value: string | number (can be either)
  • Array types:let items: string[] or Array<string>
  • Object types:let user: { name: string; age: number }
  • Function types:let onClick: () => void

Example

// Variable type annotations
let name: string = "Alice";
let age: number = 25;
let isStudent: boolean = true;
// Function parameter and return type annotations
function calculateArea(width: number, height: number): number {
return width * height;
}
// Function with no return value
function printMessage(message: string): void {
console.log(message);
}
// Optional parameters
function greetUser(name: string, age?: number): string {
if (age) {
return `Hello ${name}, you are ${age} years old`;
}
return `Hello ${name}`;
}
console.log(greetUser("Bob"));
console.log(greetUser("Charlie", 30));