TypeScript Course
TypeScript
/
Beginner

Type Annotations

Definition

Explicitly declaring the type of a variable, function parameter, or return value using the `: Type` syntax.

Explain Like I'm New

While Type Inference is TS automatically guessing the type, Type Annotations are you explicitly carving the type into stone so the compiler knows exactly what your intent is.

Real World Example

Explicitly typing function parameters: `function logMessage(msg: string)` because without it, TS doesn't know what you plan to pass in.

Common Use Cases

  • •Function parameters
  • •Function return types
  • •Uninitialized variables

Interactive Example

// Annotating parameters and return types
function calculateTax(amount: number, taxRate: number): number {
  return amount * taxRate;
}

// Annotating an uninitialized variable
let userToken: string;

// Sometime later...
userToken = "jwt_12345";

Interview Questions

basic

  • How do you annotate a function parameter?

intermediate

  • Why should you annotate function return types?

advanced

  • What is contextual typing?

Flash Cards

Question

Why annotate return types?

Click to reveal answer
Answer

While TS can infer return types, annotating them `function getNum(): number` prevents you from accidentally returning the wrong type (like returning a string or undefined) later when you modify the function body.