By using the Question Mark(?)
The optional properties can also be created by declaring the properties with a question mark symbol just after the name of the property. The question mark symbol tells the TypeScript compiler that the declared property is optional.
Syntax:
class className {
property1: type;
property2?: type;
property3?: type;
}
Example: The below code example uses the question mark symbol to define a class with optional properties in TypeScript.
class optionalPropClass {
name: string;
company?: string;
age?: number;
constructor(
name: string,
company?: string,
age?: number) {
this.name = name;
this.company = company;
this.age = age;
}
}
const employee1 =
new optionalPropClass("Employee 1");
const employee2 =
new optionalPropClass("Employee 2", "company 1");
const employee3 =
new optionalPropClass("Employee 3", "company 2", 32);
console.log(`
Employee Name: ${employee1.name},
Company: ${employee1.company ? employee1.company : "N/A"},
Age: ${employee1.age ? employee1.age : "N/A"}
`);
console.log(`
Employee Name: ${employee2.name},
Company: ${employee2.company ? employee2.company : "N/A"},
Age: ${employee2.age ? employee2.age : "N/A"}
`);
console.log(`
Employee Name: ${employee3.name},
Company: ${employee3.company ? employee3.company : "N/A"},
Age: ${employee3.age ? employee3.age : "N/A"}
`);
Output:
Employee Name: Employee 1, Company: N/A, Age: N/A
Employee Name: Employee 2, Company: company 1, Age: N/A
Employee Name: Employee 3, Company: company 2, Age: 32
Optional Property Class in TypeScript
TypeScript is an Object Oriented Programming language that allows you to create classes with optional properties which may or may not be assigned with a value.
We will discuss two different ways of creating optional property classes in TypeScript:
Table of Content
- By using the Question Mark(?)
- By assigning the properties with default values
- By Using Partial Types
Contact Us