Why use Question mark in TypeScript variable ?

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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • 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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

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



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.