By Using Partial Types
In TypeScript, you can leverage partial types to define classes with optional properties. Partial types allow you to specify that all properties of a type are optional, which aligns well with creating classes with optional properties.
Syntax:
class ClassName {
property1: type;
property2?: type;
property3?: type;
}
- property1: Required property.
- property2 and property3: Optional properties.
By using partial types, you can explicitly declare that certain properties may or may not be assigned values when creating instances of the class.
Example: In this example Class OptionalPropClass has optional properties: company and age. Instances are created with various property combinations. Displayed information shows properties or “N/A” if undefined.
class OptionalPropClass {
name: string;
company?: string;
age?: number;
constructor(
name: string,
company?: string,
age?: number
) {
this.name = name;
this.company = company;
this.age = age;
}
}
// Creating instances of OptionalPropClass with various combinations of properties
const employee1 = new OptionalPropClass("Employee 1");
const employee2 = new OptionalPropClass("Employee 2", "Company 1");
const employee3 = new OptionalPropClass("Employee 3", "Company 2", 32);
// Displaying information about the created instances
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