Lesson 33 of 60 – Optional Properties
55%

Optional Properties in TypeScript

In TypeScript, an interface normally requires all declared properties to be present when an object is created. Sometimes a property should not be mandatory. For such situations, TypeScript provides optional properties.

Note: Add a ? after the property name to make an interface property optional.

1. What is an Optional Property?

An optional property is a property that does not have to be included when an object is created.

interface Student {
    name: string;
    phone?: string;
}

Here, name is required, while phone is optional.

2. Optional Property Syntax

The syntax for an optional property is:

propertyName?: type;

Example:

interface User {
    name: string;
    email?: string;
}

3. Required vs Optional Properties

Required properties must be provided. Optional properties can be omitted.

interface Student {
    name: string;
    age: number;
    phone?: string;
}

const student: Student = {
    name: "Amit",
    age: 20
};

The object is valid even though phone is not provided.

4. Optional String Property

A string property can be made optional.

interface User {
    name: string;
    city?: string;
}

const user: User = {
    name: "Rahul"
};

The city property may be included when needed.

5. Optional Number Property

Number properties can also be optional.

interface Product {
    name: string;
    price?: number;
}

const product: Product = {
    name: "Laptop"
};

6. Optional Boolean Property

A boolean property can be optional.

interface User {
    name: string;
    active?: boolean;
}

const user: User = {
    name: "Amit"
};

7. Multiple Optional Properties

An interface can contain several optional properties.

interface Student {
    name: string;
    age?: number;
    phone?: string;
    city?: string;
}

const student: Student = {
    name: "Amit"
};

8. Optional Property with Value

An optional property can still be provided with a value.

interface Student {
    name: string;
    phone?: string;
}

const student: Student = {
    name: "Amit",
    phone: "9876543210"
};

Optional means "not required", not "not allowed".

9. Reading an Optional Property

When an optional property is accessed, it may contain a value or may be undefined.

interface User {
    name: string;
    phone?: string;
}

const user: User = {
    name: "Amit"
};

console.log(user.phone);

In this example, phone has not been provided.

10. Checking an Optional Property

You can check whether an optional property exists before using it.

interface User {
    name: string;
    phone?: string;
}

const user: User = {
    name: "Amit"
};

if (user.phone) {
    console.log(user.phone);
}

11. Using Optional Property with if

An if statement can be used to check an optional value.

interface Student {
    name: string;
    email?: string;
}

const student: Student = {
    name: "Rahul",
    email: "rahul@example.com"
};

if (student.email) {
    console.log(
        "Email: " + student.email
    );
}

12. Optional Array Property

An array property can also be optional.

interface Student {
    name: string;
    subjects?: string[];
}

const student: Student = {
    name: "Amit"
};

The subjects array is not required.

13. Optional Object Property

An entire nested object can be optional.

interface Student {
    name: string;

    address?: {
        city: string;
        pin: number;
    };
}

const student: Student = {
    name: "Amit"
};

14. Optional Function Property

A function property can also be optional.

interface User {
    name: string;
    greet?: () => void;
}

const user: User = {
    name: "Amit"
};

The greet function does not have to be supplied.

15. Calling an Optional Function Safely

Because an optional function may not exist, check it before calling it.

interface User {
    name: string;
    greet?: () => void;
}

const user: User = {
    name: "Amit"
};

if (user.greet) {
    user.greet();
}

16. Optional Property with Default Value

A default value can be used when an optional property is not supplied.

interface User {
    name: string;
    city?: string;
}

const user: User = {
    name: "Amit"
};

const city =
    user.city ?? "Patna";

console.log(city);

17. Optional Property with Nullish Coalescing

The ?? operator can provide a fallback value when an optional property is null or undefined.

interface User {
    name: string;
    phone?: string;
}

const user: User = {
    name: "Amit"
};

const phone =
    user.phone ?? "Not Available";

console.log(phone);

18. Optional Properties in Function Parameters

Interfaces with optional properties can be passed to functions.

interface User {
    name: string;
    age?: number;
}

function showUser(
    user: User
) {
    console.log(user.name);
}

showUser({
    name: "Amit"
});

19. Optional Properties and Object Updates

An optional property can be added later to a normal object.

interface Student {
    name: string;
    phone?: string;
}

let student: Student = {
    name: "Amit"
};

student.phone =
    "9876543210";

20. Optional Properties with Union Types

An optional property can also use a union type.

interface User {
    name: string;
    id?: number | string;
}

const user: User = {
    name: "Amit",
    id: "USR101"
};

The id property is optional and, when supplied, can be either a number or a string.

21. Optional Properties with Literal Types

Optional properties can be restricted to specific values.

interface User {
    name: string;
    role?: "admin" | "student";
}

const user: User = {
    name: "Amit",
    role: "student"
};

22. Optional Properties in API Data

API responses may contain properties that are not always returned. Interfaces can represent these properties as optional.

interface Product {
    id: number;
    name: string;
    price: number;
    description?: string;
    image?: string;
}

const product: Product = {
    id: 101,
    name: "Laptop",
    price: 50000
};

23. Optional Properties in React Props

Optional properties are very useful when creating reusable React components.

interface UserProps {
    name: string;
    age?: number;
}

function UserCard(
    props: UserProps
) {
    return (
        <div>
            <h3>{props.name}</h3>
            <p>{props.age}</p>
        </div>
    );
}

A component can be used without providing age.

24. Optional Properties in React Native

React Native components can also use optional properties in their interfaces.

interface UserProps {
    name: string;
    subtitle?: string;
}

const UserCard = (
    props: UserProps
) => {

    return (
        <View>
            <Text>
                {props.name}
            </Text>

            {props.subtitle && (
                <Text>
                    {props.subtitle}
                </Text>
            )}
        </View>
    );
};

25. Optional Property with Destructuring

Optional properties can be destructured from an object.

interface User {
    name: string;
    city?: string;
}

function showUser({
    name,
    city
}: User) {

    console.log(name);
    console.log(city);
}

showUser({
    name: "Amit"
});

26. Common Mistake with Optional Properties

A common mistake is assuming that an optional property always contains a value.

interface User {
    name: string;
    phone?: string;
}

const user: User = {
    name: "Amit"
};

// Check before using it
if (user.phone) {
    console.log(
        user.phone.toUpperCase()
    );
}

Always handle the possibility that an optional property is not available.

27. When Should You Use Optional Properties?

Optional properties are useful when a value is not required for every object.

  • Optional phone numbers
  • Optional profile pictures
  • Optional addresses
  • Optional descriptions
  • Optional API response fields
  • Optional React component props

28. Required and Optional Property Example

interface Student {
    id: number;
    name: string;
    course: string;

    age?: number;
    phone?: string;
    email?: string;
}

const student: Student = {
    id: 101,
    name: "Amit",
    course: "TypeScript"
};

Here, id, name, and course are required. The other properties are optional.

29. Complete Practical Example

The following example combines required and optional properties.

interface Student {
    readonly id: number;

    name: string;

    course: string;

    age?: number;

    phone?: string;

    email?: string;

    skills?: string[];

    address?: {
        city: string;
        pin: number;
    };
}

const student: Student = {

    id: 101,

    name: "Amit",

    course: "TypeScript",

    age: 20,

    skills: [
        "HTML",
        "CSS",
        "TypeScript"
    ],

    address: {
        city: "Aurangabad",
        pin: 824101
    }

};

console.log(
    student.name
);

if (student.phone) {
    console.log(
        student.phone
    );
}

if (student.address) {
    console.log(
        student.address.city
    );
}

30. Optional Properties Summary

Optional properties allow an object to omit properties that are not always required.

interface Student {
    name: string;
    age?: number;
    phone?: string;
}

The ? symbol after a property name makes that property optional.

📌 Key Points

  • Use ? to create an optional interface property.
  • Required properties must be provided when creating an object.
  • Optional properties can be omitted.
  • Optional properties may contain a value or be undefined.
  • Check optional properties before using them when necessary.
  • Optional properties can be strings, numbers, arrays, objects, functions, and other types.
  • Optional properties are useful for API response data.
  • They are commonly used for React and React Native props.
  • Optional properties can also use union and literal types.
  • Use optional properties when a value is not required for every object.

🧠 Quick Quiz

Question: Which symbol is used to make an interface property optional?