Using ‘Typeof’ Type Operator in TypeScript

Updated: January 7, 2024 By: Guest Contributor Post a comment

Introduction

TypeScript’s typeof operator is a powerful feature that allows developers to capture the type of a variable or property. This tutorial will lead you through various uses of typeof, from basic to advanced applications in your TypeScript projects.

What is typeof?

In TypeScript, typeof is a type query operator that enables you to obtain the type of a variable, property, or object member. It is especially useful when you want to reuse the type of a value implicitly without having to declare it explicitly.

Using typeof for Basic Type Queries

let exampleVar = 'Hello World';
type ExampleType = typeof exampleVar;

let anotherVar: ExampleType;
anotherVar = 'Another String'; // This is fine
anotherVar = 42; // Error: Type 'number' is not assignable to type 'string'

The example above demonstrates how you can use typeof to create a type that is the same as the type of the existing variable exampleVar.

Inferring Types for Object Properties

const user = {
    name: 'Alice',
    age: 25
};
type UserType = typeof user;

function greetUser(user: UserType) {
    console.log('Hello, ' + user.name);
}
greetUser(user);

Here, typeof is used to infer the type of the user object, which is then used as the type for the function parameter.

Type Queries on Nested Objects

const userProfile = {
    user: {
        name: 'Bob',
        age: 30
    },
    isAuthenticated: true
};
type UserNameType = typeof userProfile.user.name;

function getUserName(user: UserNameType): string {
    return user; // Expecting a string type
}

This section showcases how to drill down into nested objects using typeof to obtain specific property types.

Using typeof with Functions

function add(x: number, y: number): number {
    return x + y;
}
type AdderFunction = typeof add;

let myAdder: AdderFunction = function(x, y) { return x + y; };
myAdder(2, 3); // Returns 5

Here, typeof is used to capture the type signature of a function, allowing you to apply the same signature to other variables or functions.

Conditional Types with typeof

type MessageOf = T extends { message: unknown } ? T['message'] : never;
let errorMessage: MessageOf<{ message: string } | { alert: string };
errorMessage = ({ message: 'Error occurred' }); // OK
errorMessage = ({ alert: 'Warning!' }); // Error

This advanced example uses typeof in combination with conditional types to express more complex type relationships and constraints.

Final Words

The typeof operator in TypeScript is incredibly versatile, allowing you to create types that are firmly anchored to the runtime values of your variables and properties. It promotes type safety and consistency throughout your codebase, ensuring that your types evolve along with your data. So, as you progress in your TypeScript journey, remember to harness the power of typeof to keep your types accurate and synchronised.