TypeScript Typeof

Rana Hasnain Khan Feb 15, 2024
TypeScript Typeof

This article will discuss the typeof operator in TypeScript; we will elaborate on how it works and how it can be helpful for us.

typeof in TypeScript

TypeScript’s typeof is similar to JavaScript, but the functions are very different. The typeof transforms the different kinds in TypeScript, but typeof can convert a number, string, symbol, Boolean, etc.

The typeof can be used with any type in TypeScript. Using it, we can re-model the code, bypassing any parameter type.

We will see about the typeof in TypeScript to acknowledge it better. That is how it works.

As we know, typeof is used to deal with different types in TypeScript. Now, let’s see its syntax in detail for better acknowledgment, as shown below.

let hello = "hello world"
console.log(typeof hello === "string")

Output:

syntax of typeof in typescript

Let’s go through another example in which we will test the typeof method by passing a numerical variable, as shown below.

let num = 54
console.log(typeof num === "string")

Output:

numerical of typeof in typescript

As we can see in the line of syntax, we can straight use this typeof with the variable name we want to find. We can write our concept as per the requirement.

This section of the article will discuss this usage in detail for better acknowledgment.

As we see above, the typeof deals with multiple types in typeof in TypeScript. The typeof in TypeScript allows us to help with the numerous varieties in TypeScript, and we can re-model our previous code for various classes in TypeScript.

This part of the article will discuss using typeof in TypeScript while programming. Let’s see its uses and acknowledge them better for future use below.

Keyword Usage in TypeScript

In the above lines of code, we use the typeof keyword with the variable, and it will tell us about the type of the variable; after this, we can use this to perform any operation on it.

We are showing one example for typeof in TypeScript for a starter to acknowledge its inside working as follows.

class Test{
    demoFunction(test: any): any{
        if(typeof test === "string"){
            return test;
            }
    }
}
let testobj = new Test();
let Ans= testobj.demoFunction("This is a string");
console.log(Ans);

Output:

keyword usage in typeof in typescript

As seen in the above examples, we can test the typeof method by passing a numerical or a string variable or any other type of variable to check the type using the typeof method.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn