Open In App

TypeScript Optional Properties Type

TypeScript Opional properties type provides a way of defining the parts that are not necessarily required.

TypeScript Optional Properties Types

Syntax

propertyName? : type;

Parameters

Optional properties in TypeScript can be specified using different methods which are as follows:

Method 1: Optional properties in Interface

In TypeScript interfaces optional properties can be defined by using the '?' modifier after the property name. This indicates that a property may or may not be present on objects of that interface type.

Example: In the above example,the properties name and age are required but the property designation is optional.

interface Employee {
  name: string;
  designation?: string; // Optional property
  age: number;
}

const employee1: Employee = {
  name: "John",
  age: 30,
};

const employee2: Employee = {
  name: "Jessica",
  designation:"Developer",
  age: 25,
};

console.log(employee1); 
console.log(employee2);

Output:

InterfaceOP-OP1

Optional parameter in Interface output

Mehtod 2: Optional properties in Class

To make a property optional in a class, you can initialize it with undefined in the constructor and mark it as optional in the class definition using the '?' modifier.

Example: In the above example,the property brand is required but the property model is optional.

class Car {
  brand: string;
  model?: string; // Optional property

  constructor(brand: string, model?: string) {
    this.brand = brand;
    this.model = model;
  }
}

const car1 = new Car("Toyota");
const car2 = new Car("Ford", "Focus");

console.log(car1); 
console.log(car2); 

Output:

ClassOP-OP1

Optional parameter in Class output

Method 3: Optional properties in Type

Type aliases allow you to define optional properties in a similar way to interfaces, using the '?' modifier.

Example: In this example,the properties userId and name are required but the property email is optional.

type User = {
  userId: number;
  name:string;
  email?: String; // Optional property
};

const user1: User = {
  userId: 1001,
  name:"Anne",
  email: "anne@email.com",
};

const user2: User = {
  userId: 1002,
  name:"Smith",
};

console.log(user1);
console.log(user2);

Output:

typeOP-OP1

Optional parameter in Type output

Method 4: Optional properties in Object Literal

Only in interfaces and classes optional properties are allowed and not in object literals. But we can use optional properties in object literals by specifying that the property is optional in the type definition.

Example: In the above example,the properties name and id are required but the property email is optional.

let userAccount1: 
    { name: string, id: number, email?: string } = {
           name: 'John Smith',
           id: 31
};

let userAccount2: 
    { name: string, id: number, email?: string } = {
           name: 'John Smith',
           id: 31,
           email:"johnsmith@email.com"
};

console.log(userAccount1);
console.log(userAccount2);

Output:

OL_OP-OP!

Optional parameter in Object Literal output

Method 5: Partial Utility

In TypeScript, Partial type is a utility type that allows us to set all properties of an existing type optional. This utility is useful while working with APIs which consists of a lot of properties but only few of them are required.

Syntax:

Partial<existingType>;

Here,

Example:

type User = { 
    firstName: string, 
    lastName: string 
}
let firstUser:Partial<User> = 
    { firstName: "John" } 
let secondUser:User = 
    { firstName: "John", lastName: "Doe" }
console.log(firstUser);
console.log(secondUser);

Output:

PartialUtility-OP1

Partial Utility output

Method 6: Using Default Parameter Values

In TypeScript, you can utilize default parameter values to specify optional properties within functions or constructors. This approach can be particularly useful when you need optional properties within function parameters or constructor arguments.

Example: In this example we are following above explained approach.

// Define a function with optional properties using default parameter values
function createUser(name: string, age: number, designation: string = 'Employee') {
    return {
        name,
        age,
        designation,
    };
}

// Create users with different optional properties
const user1 = createUser('GFG', 23);
const user2 = createUser('Nikunj', 22, 'Developer');

console.log(user1);
console.log(user2); 

Output:

{ name: 'GFG', age: 23, designation: 'Employee' }
{ name: 'Nikunj', age: 22, designation: 'Developer' }
Article Tags :