Open In App

Why use Question Mark in TypeScript Variable?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The question mark in TypeScript is used to mark a variable as optional, allowing it to be omitted or set to undefined. This is commonly used in object properties and function parameters, enhancing flexibility by making variables non-mandatory. This feature helps prevent errors and ensures better handling of dynamic data.

Syntax:

function A(x?: number) {
    // Function_body
}

Example 1: This example shows the use of question marks in the TypeScript Variable.

JavaScript
function point(x?: number, y?: number){
    if(x) 
        console.log('X : ' + x);
    else 
        console.log('Value of X coordinate not given');
    if(y) 
        console.log('Y : ' + y);
    else 
        console.log('Value of Y coordinate not given');
}

Output:

Function Call: point();
Value of X coordinate not givenValue of Y coordinate not givenFunction Call : point(10);
X : 10Value of Y coordinate not given Function Call : point(10, 20);
X : 10
Y : 20

Example 2: This example shows the use of question marks in TypeScript Variable.

JavaScript
javascriptclass Hello{

    constructor(private firstName: string, private lastName?: string)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        if (lastName)
            console.log('Hello ' + this.firstName + ' ' + this.lastName);
        else
            console.log('Hello ' + this.firstName);
    }
}

// Creating an object h1
let h1 = new Hello('Shivam'); 

// Creating an object h2
let h2 = new Hello('Shivam', 'Gupta'); 

Output:

Hello Shivam
Hello Shivam Gupta

Note: A required parameter cannot follow an optional parameter. If we declare any variable as optional, all the variables on the right side of that must also be optional, otherwise, it will give an error.



Similar Reads