Skip to content
Related Articles

Related Articles

Improve Article

Why use Question mark in TypeScript variable ?

  • Difficulty Level : Hard
  • Last Updated : 30 Jan, 2020
Geek Week

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.

    Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




    My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :