0
0
Typescriptprogramming~5 mins

Optional properties in Typescript

Choose your learning style9 modes available
Introduction

Optional properties let you create objects where some details can be left out. This makes your code flexible and easier to use.

When you want to describe a user profile where some info like phone number might not be given.
When creating settings where some options can be skipped and default values used.
When working with forms where some fields are not required.
When defining data models that can have extra or missing parts depending on the case.
Syntax
Typescript
interface Example {
  requiredProp: string;
  optionalProp?: number;
}

The question mark ? after the property name means it is optional.

Optional properties can be missing when creating objects of this type.

Examples
The age property is optional. You can create a Person with or without age.
Typescript
interface Person {
  name: string;
  age?: number;
}
Both p1 and p2 are valid because age is optional.
Typescript
const p1: Person = { name: "Alice" };
const p2: Person = { name: "Bob", age: 30 };
Multiple optional properties can be added to an interface.
Typescript
interface Config {
  url: string;
  timeout?: number;
  debug?: boolean;
}
Sample Program

This program shows two products. The first one has no description, the second one does. Both are valid because description is optional.

Typescript
interface Product {
  id: number;
  name: string;
  description?: string;
}

const product1: Product = { id: 1, name: "Book" };
const product2: Product = { id: 2, name: "Pen", description: "Blue ink pen" };

console.log(product1);
console.log(product2);
OutputSuccess
Important Notes

Optional properties help avoid errors when some data is missing.

When accessing optional properties, you might want to check if they exist first to avoid runtime errors.

Summary

Optional properties use ? to mark them as not required.

They make interfaces flexible and easier to work with.

You can create objects with or without optional properties.