paint-brush
Using the typeof Operator in TypeScriptby@smpnjn
14,210 reads
14,210 reads

Using the typeof Operator in TypeScript

by Johnny SimpsonJuly 4th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In TypeScript, we already have a vanilla `typeof` operator which can be used to find the type of anything. Typeof` can also be combined with `ReturnType` to get the returned value of a function. The most basic application of typeof` in TypeScript is the creation of new basic types. It can be useful when creating custom types that have many properties where the properties should match existing variable types. The typeof operator is used to differentiate between the **value** and **type** of an object.

Company Mentioned

Mention Thumbnail
featured image - Using the typeof Operator in TypeScript
Johnny Simpson HackerNoon profile picture


In Javascript, we already have a vanilla typeof operator which can be used to find the type of anything:

let x = "hello world";
console.log(typeof x); // Returns "string"


With TypeScript being a strongly typed language, typeof takes on a slightly different meaning. Although all the basic Javascript typestypeof functionality remains the same, it also gets some additional, useful features. Let's look at how typeof works in TypeScript.

How typeof works in TypeScript

The most basic application of typeof in TypeScript is the creation of new basic types. If we are defining our own custom types in TypeScript, we can use typeof to copy the type of an existing item. A simple example where we take a number, and create a custom type off the back of it looks like this:


let x = 1234;

// Custom type aNumber
type aNumber = typeof x;


This can be useful if variable types may vary, and we want to match a specific variable. It can also be useful when creating custom types that have many properties where the properties should match existing variable types:

let x = 1234;
let y = "string";

// Custom type aNumber
type myType = {
    name: typeof y,
    age: typeof x,
}


As you can see, typeof basically gives us a way to differentiate between the value and type of an existing object. It can also be combined with ReturnType quite intuitively, to get the returned value of a function, to ensure type consistency when expecting values from functions:

function myFunction(x: string, y: string) {
    return { 
        firstName: x,
        lastName: y
    }
}
type nameType = ReturnType<typeof myFunction>;


I have covered ReturnType in more detail in this article, so check that out if you want to learn more. Similarly, you can learn more about TypeScript here.


Also Published here