TypeScript / TypeScript Interfaces and Types

Optional and Readonly Properties in Interfaces

In this tutorial, we'll explore optional and readonly properties in TypeScript interfaces, which allow us to create flexible and robust types.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers defining and using interfaces and type aliases in TypeScript for object shapes and contracts.

Tutorial: Optional and Readonly Properties in Interfaces

1. Introduction

Goal of the Tutorial

In this tutorial, we'll learn about optional and readonly properties in TypeScript interfaces. We'll understand their importance and use cases in making our TypeScript code more flexible and robust.

What You Will Learn

By the end of this tutorial, you will:
- Understand what optional and readonly properties are in TypeScript interfaces
- Learn how to declare and use these properties
- Be able to write more flexible and safer TypeScript code

Prerequisites

Basic understanding of TypeScript and interfaces is required to follow this tutorial.

2. Step-by-Step Guide

Optional Properties

Optional properties in an interface allow us to create objects that may not include all properties defined in the interface. They are declared with a ? after the property name.

Example:

interface Employee {
  id: number;
  name: string;
  role?: string; // this is an optional property
}

Readonly Properties

Readonly properties in an interface are properties that cannot be changed after an object is created. These properties are declared with the readonly keyword.

Example:

interface Employee {
  readonly id: number;
  name: string;
  role?: string;
}

3. Code Examples

Example 1: Optional Properties

interface Employee {
  id: number;
  name: string;
  role?: string; // optional property
}

// creating an object
let john: Employee = { id: 1, name: 'John' };

console.log(john); 
// Expected output: { id: 1, name: 'John' }

In the above code, we didn't provide a value for the role property while creating the john object, and it's completely fine because role is an optional property.

Example 2: Readonly Properties

interface Employee {
  readonly id: number;
  name: string;
  role?: string;
}

// creating an object
let john: Employee = { id: 1, name: 'John', role: 'Developer' };

john.id = 2; // This will give a compile-time error

In the above code, we're trying to change the value of the id property which is a readonly property so it gives a compile-time error.

4. Summary

In this tutorial, we learned about optional and readonly properties in TypeScript interfaces. Optional properties allow us to create objects without needing all properties of the interface. Readonly properties make sure that a property value cannot be changed after an object is created.

For further learning, you can explore how these properties behave with classes and when they are part of an array or a function.

5. Practice Exercises

  1. Create a Person interface with firstName, lastName(optional), and age(readonly) properties. Then create an object of this interface.

  2. Create a Vehicle interface with id(readonly), type, brand and modelYear(optional) properties. Create an object of this interface and try to change the id property.

Solutions

1.

interface Person {
  firstName: string;
  lastName?: string;
  readonly age: number;
}

let john: Person = { firstName: 'John', age: 30 };

2.

interface Vehicle {
  readonly id: number;
  type: string;
  brand: string;
  modelYear?: number;
}

let car: Vehicle = { id: 1, type: 'Car', brand: 'Toyota', modelYear: 2020 };

car.id = 2; // This will give a compile-time error

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help