Skip to content
Related Articles

Related Articles

Why use Question mark in TypeScript variable ?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 30 Jan, 2020

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.


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

Below examples illustrate the above approach:

  • Example 1:

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


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

    class Hello{
        constructor(private firstName: string, private lastName?: string)
            this.firstName = firstName;
            this.lastName = lastName;
            if (lastName)
                console.log('Hello ' + this.firstName + ' ' + this.lastName);
                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.

    My Personal Notes arrow_drop_up
    Recommended Articles
    Page :

    Start Your Coding Journey Now!