Open In App

Why use Question mark in TypeScript variable ?

Improve
Improve
Like Article
Like
Save
Share
Report

Question marks on TypeScript variable are used to mark that variable as an optional variable. If we put the question mark when declaring a variable that variable becomes optional. The optional parameters will have value as undefined when unused.

syntax:

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

Below examples illustrate the above approach:

  • Example 1:




    <script>
    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');
    }
    </script>

    
    

  • Output:
    Function Call: point();
    Value of X coordinate not given
    Value of Y coordinate not given
    
    Function Call : point(10);
    X : 10
    Value of Y coordinate not given
    
    Function Call : point(10, 20);
    X : 10
    Y : 20
    
  • Example 2:




    <script>
    class 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'); 
    </script>

    
    

  • 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.



    Last Updated : 30 Jan, 2020
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
    Similar Reads