runtime.boot

Full Stack Systems
Production Mindset

CodeWithMihir

Engineering thoughtful products from interface to infrastructure.

CodeWithMihir

TypeScript Tutorial

TypeScript Type Annotations: Variables, Functions, Arrays, and Objects

Learn TypeScript type annotations with beginner-friendly examples for variables, function parameters, return types, arrays, objects, and common mistakes.

Welcome back! I am Mihir, and in this lesson we will learn Type Annotations in TypeScript.

Type annotations are one of the first TypeScript concepts every beginner should understand. They let you explicitly tell TypeScript what type of value a variable, function parameter, return value, array, or object should have.


What is a Type Annotation?

A type annotation is a way to manually write the type of a value.

Syntax:

let variableName: type = value;

Example:

let username: string = "Mihir";
let age: number = 25;
let isLoggedIn: boolean = true;

The part after the colon is the type annotation:

: string
: number
: boolean

Why Use Type Annotations?

Type annotations help TypeScript understand your intention.

let price: number = 999;
price = "free";

TypeScript warns because price should always be a number.

This helps prevent accidental type changes.


Variable Type Annotations

String

let courseName: string = "TypeScript";

A string stores text.

courseName = "JavaScript";
courseName = 100;

The second assignment is invalid because 100 is a number.

Number

let totalPrice: number = 1499;
let rating: number = 4.8;

TypeScript uses number for integers and decimals.

let count: number = 10;
let percentage: number = 99.5;

Boolean

let isPublished: boolean = true;
let hasAccess: boolean = false;

A boolean can only be true or false.


Function Parameter Annotations

Function parameters should usually have type annotations.

function greet(name: string) {
  return `Hello, ${name}`;
}

greet("Mihir");
greet(100);

TypeScript warns on greet(100) because the function expects a string.

Multiple Parameters

function add(a: number, b: number) {
  return a + b;
}

console.log(add(10, 20));

Both a and b must be numbers.


Function Return Type Annotations

You can also annotate what a function returns.

function add(a: number, b: number): number {
  return a + b;
}

The : number after the parentheses means the function must return a number.

Invalid example:

function add(a: number, b: number): number {
  return "done";
}

TypeScript warns because the function promises to return a number but returns a string.


Void Return Type

If a function does not return anything, use void.

function logMessage(message: string): void {
  console.log(message);
}

void means the function performs an action but does not return a useful value.

Common examples:

  • logging
  • event handlers
  • sending notifications
  • updating UI state

Array Type Annotations

There are two common ways to type arrays.

Syntax 1

let scores: number[] = [90, 85, 100];
let names: string[] = ["Mihir", "Aarav", "Riya"];

Syntax 2

let scores: Array<number> = [90, 85, 100];
let names: Array<string> = ["Mihir", "Aarav", "Riya"];

Both are valid.

Most beginners prefer number[] and string[] because they are shorter.

Invalid example:

let scores: number[] = [90, 85, "full"];

TypeScript warns because "full" is not a number.


Object Type Annotations

You can annotate object shapes directly.

let user: {
  name: string;
  age: number;
  isAdmin: boolean;
} = {
  name: "Mihir",
  age: 25,
  isAdmin: true,
};

This works, but it can become hard to read if the object is large.

For reusable object shapes, use a type alias:

type User = {
  name: string;
  age: number;
  isAdmin: boolean;
};

const user: User = {
  name: "Mihir",
  age: 25,
  isAdmin: true,
};

This is cleaner and reusable.


Optional Property Annotations

Sometimes a property may not exist.

Use ? to make it optional.

type User = {
  name: string;
  email: string;
  phone?: string;
};

const userOne: User = {
  name: "Mihir",
  email: "mihir@example.com",
};

const userTwo: User = {
  name: "Aarav",
  email: "aarav@example.com",
  phone: "9876543210",
};

phone?: string means phone can be a string or missing.


Union Type Annotations

A value can sometimes have more than one possible type.

let userId: string | number;

userId = "user_101";
userId = 101;

This means userId can be a string or a number.

Another example:

let status: "pending" | "success" | "error";

status = "pending";
status = "success";
status = "failed";

TypeScript warns on "failed" because it is not allowed.


When Type Annotations Are Useful

Use type annotations when:

  • Function parameters need clear types
  • Function return type should be guaranteed
  • A variable is declared before assignment
  • Object shapes need to be explicit
  • A value can have multiple possible types
  • You want better documentation for other developers

Example:

let selectedUserId: number;

selectedUserId = 101;

Without annotation, TypeScript cannot know what type you plan to assign later.


When Type Annotations Are Not Needed

TypeScript can often infer types automatically.

let course = "TypeScript";
let duration = 30;
let active = true;

TypeScript already knows:

  • course is a string
  • duration is a number
  • active is a boolean

So this is unnecessary:

let course: string = "TypeScript";

It is not wrong, but it can be redundant.

We will learn this properly in the next lesson: Type Inference.


Common Mistakes

Using Wrong Capitalization

Use lowercase primitive types:

let name: string = "Mihir";

Avoid:

let name: String = "Mihir";

For primitives, prefer string, number, and boolean.

Overusing any

let data: any = "Mihir";
data = 25;
data = true;

any turns off TypeScript safety for that value.

Use it rarely.

Annotating Everything

This is okay:

let name = "Mihir";

TypeScript understands it is a string.

You do not need to manually annotate every simple variable.


Quick Reference Summary

AnnotationExample
Stringlet name: string = "Mihir"
Numberlet age: number = 25
Booleanlet active: boolean = true
Function parameterfunction greet(name: string)
Function returnfunction add(): number
Voidfunction log(): void
Arraylet scores: number[]
Objectconst user: User
Optional propertyphone?: string
Union`id: string

Practice

Create types for a blog post:

type BlogPost = {
  title: string;
  slug: string;
  views: number;
  published: boolean;
};

function printPost(post: BlogPost): void {
  console.log(`${post.title} has ${post.views} views.`);
}

const post: BlogPost = {
  title: "TypeScript Type Annotations",
  slug: "typescript-type-annotations",
  views: 1000,
  published: true,
};

printPost(post);

Try changing views to a string and see what TypeScript says.


What You've Learned

You now understand:

  • What type annotations are
  • How to annotate variables
  • How to type function parameters
  • How to type function return values
  • How to type arrays and objects
  • How optional properties work
  • How union annotations work
  • When annotations are useful
  • When TypeScript can infer types automatically

What's Next?

In the next lesson, we will learn Type Inference.

You will see how TypeScript automatically understands types without you writing annotations everywhere.


Need Help?

  • Have questions, confusion, or want to know more? Contact me

Type annotations are the foundation. Once you understand them, the rest of TypeScript becomes much easier.