Open In App

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:

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




    Article Tags :