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 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);
}
}
let h1 = new Hello( 'Shivam' );
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
Share your thoughts in the comments
Please Login to comment...