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.

Javascript
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:

Optional parameter in Interface output

TypeScript Optional Properties Type

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

Similar Reads

TypeScript Optional Properties Types

Optional Properties are properties that are not required mandatorily and can be omitted when not needed.In TypeScript, you can define optional properties in an interface, in a class, in an object, or in a type by using the ‘?’ modifier after the property name. Optional properties allow to specify that a property may or may not be present on an object of that type. Optional Properties can be useful when not all properties are required....

Syntax

propertyName? : type;...

Parameters

propertyName: Name of the property that can be optionaltype: Type of the property?: Symbol which specifies that it is an optional property...

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....

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....

Method 3: Optional properties in Type

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

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....

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....

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....

Contact Us