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.
Section overview
5 resourcesCovers 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
-
Create a
Personinterface withfirstName,lastName(optional), andage(readonly) properties. Then create an object of this interface. -
Create a
Vehicleinterface withid(readonly),type,brandandmodelYear(optional) properties. Create an object of this interface and try to change theidproperty.
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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article