TypeScript Annotations


TypeScript: Type Annotations

Type annotations let you tell TypeScript exactly what kind of data a variable or function should use.


What Are Type Annotations?

Sometimes, you want to be very clear about what kind of value you're expecting.

Type annotations let you label a variable or a function with its expected type.

It’s like giving TypeScript instructions:

“This should always be a number” or “This function must return a string.”

How to Write One

You add a colon : after the variable name, followed by the type.

let username: string = "Sahand"; 
let age: number = 30; 
Let isOnline: boolean = true; 

TypeScript will now keep an eye on those variables to make sure their types never change.


Function Annotations

You can also use annotations in functions — for both parameters and return values.

function greet(name: string): string {  
       return "Hello, " + name; 
} 
  • name: string means the function expects a string as input.
  • : string after the parentheses means the function returns a string.

Why Use Them?

  • Makes your code easier to read
  • Helps catch bugs early
  • Great for teams or large codebases
  • Works well when TypeScript can't figure out the type on its own

Tip

Use annotations when:

  • Variables have no initial value
  • Parameters and return types need to be clear
  • Working with complex data structures (like objects or functions)

Prefer Learning by Watching?

Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:

What You'll Learn:
  • 📌 Type Annotations - TypeScript Programming Tutorial #1
  • 📌 Type Annotation & Type Inference | String Templates | TypeScript Tutorial
Previous Next