TypeOf in TypeScript

A typeOf keyword returns the type of an identifier in TypeScript. It also acts as a Type Guard narrowing the Type in the scope where we use it.

Using TypeOf

The syntax of the TypeOf is as shown below. It returns the type of the identifier, which we place right next to it.

For Example

As the TypeOf returns the type, we can use it in variable declaration as shown below.

You can also use it declare anonymous types.

For example, we have not provided the type to the variable person. The TypeScript infers the type from the initialization as { code: string, name: string }. We can create another variable employee with the same type as person by using the TypeOf query (typeof person).

TypeOf correctly returns the type in case of number, string, boolean, symbol, undefined, function. Everything else is object. That also includes null

Typeof As Type Guard

TypeOf operator also acts like a Type Guard, Similar to instanceOf.

For example, the following function formatAmount appends Rs. to the money sent in its argument. The user can either pass the money as union type of number and string. If the money is of type string, we need to use parseInt to convert it to a number But since the parseInt expects a string the code throws a compile-time error.

We can use the typeof money == "string" to check if the type of the money is equal to string. If it is true then use the parseInt method in the if block. The TypeScript will not throw an error for parseInt, because it now knows that the type of money is string inside the if block.

You can see from the following image. As you hover over the money variable outside the if block, it shows it as union type of number | string. Inside the if block it treats as string and in the else block it treats as number.

TypeOf in TypeScript Acts a a Type Guard

Use with Type Aliases

The TypeScript allows us to create Type Aliases using the keyword type. We can combine it with the TypeOf to create Type Aliases for anonymous types

In the following code, we create a Type Alias personType and assign it the type using the typeof person. Now the personType becomes type alias for the type { code: string, name: string }. We can use it to create variables as shown below.


Advanced Types

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top