Understanding Optional Properties in Typescript

In TypeScript, you can define optional properties in object types using the ? modifier. This indicates that the property may or may not be present in the object.

Syntax

type MyType = {
  requiredProp: string; // Required property
  optionalProp?: number; // Optional property
};

const obj1: MyType = {
  requiredProp: "Hello",
};

const obj2: MyType = {
  requiredProp: "World",
  optionalProp: 42,
};

Key Points

  1. Optional Properties:
    • Defined using the ? modifier.
    • Can be omitted when creating objects.
  2. Accessing Optional Properties:
    • TypeScript enforces a check or allows the property to be undefined.
    • You may need to check for the property before using it.
    const obj: MyType = { requiredProp: "Test" }; if (obj.optionalProp !== undefined) { console.log(obj.optionalProp.toFixed(2)); }
  3. Default Values:
    • You can use default values with optional properties using the || or nullish coalescing (??) operator.
    const value = obj.optionalProp ?? 0; console.log(value);
  4. Type Compatibility:
    • Objects with optional properties are compatible with objects that have the property omitted or undefined.

Example: Optional Properties in Functions

type User = {
  name: string;
  age?: number;
};

function greet(user: User): void {
  const ageInfo = user.age ? ` who is ${user.age} years old` : "";
  console.log(`Hello, ${user.name}${ageInfo}!`);
}

greet({ name: "Alice" });
greet({ name: "Bob", age: 25 });

Optional Properties in Index Signatures

You can also use optional properties in combination with index signatures for more flexible object types.

type Flexible = {
  id: string;
  [key: string]: string | number | undefined;
};

const flexibleObj: Flexible = {
  id: "123",
  name: "John",
  age: 30,
};

Sample Example with Optional Properties

type Student = {name :string, age :number, passportNo?:string};
const students:Student[] = [{name:"Keshav",age:35,passportNo:"N23535"},{name:"Stephen",age:33},{name:"Ravi",age:30}];
for(let student of students) {
console.log("Student Details - Name :"+student.name+", Age : "+student.age+", PassportNumber: "+(student.passportNo ?? "Not Available"));
}

Summary

Optional properties in TypeScript are a powerful way to create flexible object types while maintaining type safety. They are useful for scenarios where not all properties are required, like optional configuration objects or incomplete data structures.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *