By assigning the properties with default values
If the properties of a class are initialized with some initial or default values, then either you pass or omit the values of those properties while creating an instance will not throw an error and it uses the provided default values in the case you omit passing the values.
Syntax:
class className {
property1: type;
property2: type = initialValue;
property3: type = initialValue;
}
Example: The below code example implements the default values approach to create optional properties class in TypeScript.
class optionalPropClass {
name: string;
company: string = "w3wiki";
age: number = 25;
constructor(
name: string,
company: string = "w3wiki",
age: number = 25) {
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},
Age: ${employee1.age}
`);
console.log(`
Employee Name: ${employee2.name},
Company: ${employee2.company},
Age: ${employee2.age}
`);
console.log(`
Employee Name: ${employee3.name},
Company: ${employee3.company},
Age: ${employee3.age}
`);
Output:
Employee Name: Employee 1, Company: w3wiki, Age: 25
Employee Name: Employee 2, Company: company 1, Age: 25
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