typeof type operator in Typescript

ยท

3 min read

typeof type operator in Typescript

typeof operator is used to get type of (I'd prefer to say Shape of) operand.

If you want to learn about typeof in reference to Javascript then you can visit typeof operator in javascript.

Syntax of typeof operator in Typescript

Typescript typeof operator is similar to typeof in Javascript.

const name = "decpk";
const nameType = typeof name;
console.log(nameType); // string

Above code snippet demonstrate typeof in Javascript. Surprisingly it also works in Typescript too. So using typeof in Typescript is somewhat similar if our goal is to get the type of any value.

But in Typescript we can use it much more and in many exciting places. Let's explore.

Create custom type with typeof

You can create custom type from any value and also assign it to some other type also.

let userName = "decpk";
type TName = typeof userName; // string

In the above code snippet, we have used typeof to get typeof userName which is string and finally it gets assigned to TName type.

Well above example looks like trivial but it can make much more sense if we try to do this in a large object.

let userName = "Praveen kumar";
let userAge = 18;
let isDeveloper = true;

type TUser = {
    // creating types from already existing values
    userName: typeof userName;
    userAge: typeof userAge;
    isDeveloper: typeof isDeveloper;
}

// Defining function which takes user of type TUser
// and returns whatever type of userName gonna be
function getUserName(user: TUser): TUser["userName"] {
    return user.userName;
}

const devUser = getUserName({
    userAge,
    userName,
    isDeveloper
})

Above example is best example to understand use of typeof in defining complex type. In this example the type of userName, userAge or isDeveloper going to be contribute in defining type of TUser.

Now type of userName is just string but what if in future requirement gets changed and it will be an object which contain firstName and lastName then we just have to make small changes and we are good to go.

let userName = {
    firstName: "Praveen",
    lastName: "Kumar"
};

So we just have to change userName and types will get automatically evaluated from its value. Isn't this great. It makes our code maintainable and less error prone.

typeof with Objects

We can evaluate type of complex object using typeof type operator also.

Let say you are importing an object from some library or from other's code base and you don't know its type then you can create its type using typeof type operator.

const userReduxActions = {
    CREATE: "CREATE",
    READ: "READ",
    UPDATE: "UPDATE",
    DELETE: "DELETE"
} as const;

type TUserReduxActions = typeof userReduxActions;

So when you hover over TUserReduxActions its type will gets evaluated as:

So we don't have to define type explicitly. Also it will get updated as soon as something changes in userReduxActions object.

typeof in functions

We can also use typeof type operator to get type of function also

let user = {
    name: {
        firstName: "Praveen",
        lastName: "Kumar"
    },
    age: 100,
    isDeveloper: true,
    knownProgrammingLanguage: ["JS", "TS"]
}

type TUser = typeof user;

function printUserDetails(user: TUser): string {
    return `User ${user.name.firstName} is a ${user.isDeveloper ? "Developer": "Designer"}`
}

type TPrintUserDetailsFn = typeof printUserDetails;

When we hover over TPrintUserDetailsFn then it show type as:

It is exactly same as evaluating type of an object. But it will get interesting when you want to find what exactly is the type of parameters of printUserDetails or return type of printUserDetails function.

We can easily find it using Parameters and ReturnType Typescript utility which accepts function type as a generic parameter.

Arguments of printUserDetails function is

and return typeof printUserDetails function is

which is dynamically evaluated and gets updated if number or type of arguments gets changed.

We can use ReturnType and Parameters on any function(Inbuilt or library function).

I hope you love this article. See you in next article ๐Ÿ™‚

Did you find this article valuable?

Support decpk by becoming a sponsor. Any amount is appreciated!

ย