Open In App

How to Declare Optional Properties in TypeScript ?

The optional properties are the properties that may or may not be present in an object or assigned with a value. You can define the optional properties for different data types in TypeScript like interfaces, type aliases, classes, etc. In TypeScript, you can use the question mark (?) symbol to declare the optional properties just after the name of the property. TypeScript won’t throw any error if you don’t pass or use the optional property in the object.

Syntax:

interface interface_name {
property1: type1;
property2?: type2; // Optional property
}

Example: The below code will explain how you can declare an optional property in TypeScript.




interface myInterface {
    name: string;
    desc: string;
    est?: number;
}
 
const myObj: myInterface = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
}
console.log(myObj);

Output:

{
name: "GeeksforGeeks",
desc: "A Computer Science Portal"
}
Article Tags :