EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Question Mark
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript Question Mark

By Asapu HarikaAsapu Harika

TypeScript Question Mark

Introduction to TypeScript Question Mark

TypeScript question mark are used on variables to mark it as an optional parameter. When declaring a TypeScript variable, the declared variable becomes an optional parameter. This optional parameter will have undefined if not used. In TypeScript 3.7 version, we have a concept of optional chaining, which lets the user write code where TypeScript can stop running of such expression which return null or undefined. This is how ‘TypeScript question mark’ ‘?’ came into picture. As question mark marks the variable as optional, but any optional parameter should follow with required parameter.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,198 ratings)

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

function sample_A(x ?: string) {
// function’s logic here
}

Function here requires any parameter to test if null or undefined.

One of the most important point which has been resolved with TypeScript 3.7 version is continuously checking of variables or expressions for being null or undefined

Examples

Let us consider few examples below to know much better on the implementation and the use of TypeScript question mark.

Example #1: Simple TypeScript expression check

class addition{
constructor( private x?: number, private y?: number){
if(x)
console.log('X value is: ' + x);
else
console.log('Value of X is not defined or null');
if(y)
console.log('Y value is: ' + y);
else
console.log('Value of Y is not defined or null');
}
}
// object creation for addition1
let addition1 = new addition(2, 3);
// object creation for addition2
let addition2 = new addition(3, );
// object creation for addition3
let addition3 = new addition( , );

Output:

TypeScript Question Mark 1

Here, we have taken 2 string values as optional. So for the first object, given both the values. For second object, only x value was provided and hence Y value returned was null. For object 3, both the values were undefined or null

Example #2: check with string expression

class Employee{
constructor(private age: number, private name?: string)
{
this.age = age;
this.name = name;
if (name)
console.log('Hi, ' + this.name + ', you fall under below ' + this.age + ' category');
else
console.log('Hi, you belong to age ' + this.age);
}
}
// object creation for emp1
let emp1 = new Employee(23);
// object creation for emp2
let emp2 = new Employee(20, 'Sharma');

Output:

TypeScript Question Mark 2

So here, we are using TypeScript question mark to check the ‘name’ type if it a string and has a value else will return undefined or null. Will have a look in the next example.

Example #3: TypeScript question mark expression check returning null or undefined.

class Student{
constructor(private name?: string, private stndrd?: string, private id: number)
{
this.name = name;
this.stndrd = stndrd;
this.id = id;
if (name || stndrd)
console.log('Hi, ' + this.name + ', are you studying in ' + this.stndrd);
else
console.log('Hi, your ID ' + this.id + ' has not been registered yet');
}
}
// object creation for student1
let student1 = new Student('Sahasra', '5th', 456);
// object creation for student2
let student2 = new Student('', '', 789);
// object creation for student3
let student3 = new Student('Reshma', '', 123);
// object creation for student4
let student4 = new Student('', '9th', 567);
// object creation for student5
let student5 = new Student('Suresh', '9th', );

Output:

TypeScript Question Mark 3

So here we are trying to show how an expression is checked and returns null as seen above in output.

In log 3, we see that stndrd value has not been defined and hence it is null there.

In log 4, we see that name value has not been defined, and hence it is null there

In log 5, id value is not defined but as per the TypeScript question mark, we are not checking for id value.

We even have 2 Errors in our code, These two are considered to be the main Rule for TypeScript question mark

rules

  1. We have put the required parameter after the optional parameter, i.e. ID has been put after the required parameters ‘name’ and ‘stndrd’.
  2. And in last object creation, we have given only 2 parameters but the object requires 3 as ID is as required parameter.

If a user declares any variable as optional parameter, all of the other variables to the right should be must an optional parameter else will give an error as above. In brief, Required parameter can not follow an optional parameter.

It is also called as ‘Elvis operator’ or may be we can say it is named as ‘Elvis’ by one of the Microsoft Representative. As it is supported with TypeScript 3.7 version, called Optional chaining. This variant, the existential operator ‘?.’ is used to soak up all the null references.

With this, we shall conclude the topic ‘TypeScript question mark’. We have seen what TypeScript question mark is and its syntax. Parameters required and how optional and required parameters are marked using question mark. We have practiced on a few examples above which are much more enough to get know on this concept for further use. Also, we have seen the errors which we face which are the actual Rules of the TypeScript question mark to be noted.

Recommended Articles

This is a guide to TypeScript Question Mark. Here we discuss Introduction, syntax, and examples with code implementation. You can also go through our other suggested articles to learn more –

  1. TypeScript Array
  2. TypeScript Versions
  3. What is TypeScript?
  4. TypeScript Types
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more