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 typeof
Secondary Sidebar
TypeScript Tutorial
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • 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
  • 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 typeof

By Shalu SharmaShalu Sharma

TypeScript typeof

Definition of TypeScript typeof

typeof in TypeScript has the same name like JavaScript but functions differently. typeof is used to differentiate between the different types in TypeScript. By the use of typeof we can differentiate between number, string, symbol, Boolean, etc. typeof can be used with any type in TypeScript, by the use of it we can re-use the code by passing any parameter type. In the coming section, we will see more about the typeof in TypeScript to understand it better.

Syntax:

As we know typeof is a keyword that is used to deal with different types in TypeScript. Let’s see its syntax in detail for better understanding see below;

typeof variable === "your_type"

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As you can see in the above line of syntax we can directly use this typeof with the variable name which we want to calculate. After this, we can write our own logic as per the requirement. In the coming section of the article, we will discuss more this usage in detail for better understanding.

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,754 ratings)

How does typeof work in TypeScript?

As we already know that typeof is used to deal with several types in typeof in TypeScript. This allows us to help us with the various type in TypeScript, we can reuse our same code for multiple type in TypeScript. In this section, we will see how to use this while programming in TypeScript. Let’s see its usage and understand it better for future use see below;

Keyword usage:

typeof variable_name //

In the above lines of code, we are using typeof keyword with the variable it will tell us the type of variable after this we can use this to perform any operation on it. Now see one sample example for typeof in TypeScript for beginners to understand its internal working see below;

e.g. :

class Demo{
testFunction(val: any): any{
if(typeof val === "string"){
// your logic will go here ..
return val;
}
}
}
let demoobj = new Demo();
let result= demoobj.testFunction("i am string !!");
console.log(result);

In the above example, we are creating one function which accepts any type of parameter. Inside the ‘Demo’ class we have created one function named ‘testFunction’. Inside this function, we are using typeof keyword to compare the type of the variable being passed. typeof will return us the type of the parameter. This is similar to the instanceOf keyword already available. After the comparison, we can write our own logic as per the requirement. At the last to call the function in TypeScript we are creating an object of the class and calling the function. This function we have created takes one parameter, this parameter can be of any type because we have assigned the type as ‘any’ in the function declaration. This is how it works in TypeScript like any other programming language. It has some benefits as well let’s discuss them each one by one;

1) By using typeof in TypeScript we can easily make checks which can help us to get any exception further exception if we try to cast them incorrectly.

2) But making small checks we can reuse the code for any different type in TypeScript.

Examples

In this example we are trying to use the typeof with numbers in Typescript, if the passes parameter matched with the string type then it will return the value otherwise nothing will be printed. This is a sample example for beginners to understand how to use and check the typeof with numbers in Typescript.

Example #1

Code:

class Demo{
testFunction(val: any): any{
if(typeof val === "string"){
return val;
}
}
}
console.log("Demo to show the usage of typeof in Typescript !!");
let demoobj = new Demo();
let result1 = demoobj.testFunction("i am string !!");
let result2 = demoobj.testFunction("i am string two !!");
let result3 = demoobj.testFunction("i am string three !!");
console.log("printing result of the function after typeof !!");
console.log("result one is::" +result1);
console.log("result two is::" +result2);
console.log("result three is::" +result3);

Output:

TypeScript typeof 1

Example #2

In this example, we are trying to use the typeof with numbers in Typescript, if the passes parameter matched with the number type then it will return the value otherwise nothing will be printed. This is a sample example for beginners to understand how to use and check the typeof with numbers in Typescript.

Code:

class Demo{
testFunction(val: any): any{
if(typeof val === "number"){
return val;
}
}
}
console.log("Demo to show the usage of typeof in Typescript !!");
let demoobj = new Demo();
let result1 = demoobj.testFunction(100);
let result2 = demoobj.testFunction(400);
let result3 = demoobj.testFunction(500);
let result4 = demoobj.testFunction(500);
let result5 = demoobj.testFunction(500);
console.log("printing result of the function after typeof !!");
console.log("result one is::" +result1);
console.log("result two is::" +result2);
console.log("result three is::" +result3);
console.log("result four is::" +result4);
console.log("result five is::" +result5);

Output:

TypeScript typeof 2

Example #3

In this example, we are trying to use the typeof with numbers in Typescript, if the passes parameter matched with the boolean type then it will return the value otherwise nothing will be printed. This is a sample example for beginners to understand how to use and check the typeof with numbers in Typescript.

Code:

class Demo{
testFunction(val: any): any{
if(typeof val === "boolean"){
return val;
}
}
}
console.log("Demo to show the usage of typeof in Typescript !!");
let demoobj = new Demo();
let result1 = demoobj.testFunction(true);
let result2 = demoobj.testFunction(false);
let result3 = demoobj.testFunction(true);
let result4 = demoobj.testFunction(false);
let result5 = demoobj.testFunction(true);
console.log("printing result of the function after typeof !!");
console.log("result one is::" +result1);
console.log("result two is::" +result2);
console.log("result three is::" +result3);
console.log("result four is::" +result4);
console.log("result five is::" +result5);

Output:

TypeScript typeof 3

Conclusion

In the typeof keyword easy to use and understand. We can easily check the type if the parameter by simply using the typeof keyword before the variable name. This is very handy to use with variables in TypeScript. We can compare integer, number, Boolean, symbol, undefined, string, object, etc. by using typeof in Typescript.

Recommended Articles

This is a guide to TypeScript typeof. Here we discuss Definition, How does typeof work in TypeScript? and examples with code implementation. You may also have a look at the following articles to learn more –

  1. TypeScript Functions
  2. TypeScript Array
  3. TypeScript Operators
  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