0
0
Typescriptprogramming~5 mins

Typeof operator in type context in Typescript

Choose your learning style9 modes available
Introduction

The typeof operator in type context helps you get the type of a variable or value. It makes your code safer by reusing existing types without repeating them.

When you want to create a new variable with the same type as an existing one.
When you want to avoid writing the type manually and keep types consistent.
When you want to use the type of a constant or object property in another place.
When you want to make your code easier to update by linking types automatically.
Syntax
Typescript
type NewType = typeof existingVariable;

The typeof here is different from the JavaScript typeof operator that returns a string.

This typeof is used only in TypeScript's type annotations.

Examples
This creates a type AgeType that is the same as the type of age, which is number.
Typescript
const age = 30;
type AgeType = typeof age;
This creates a type UserType matching the shape of the user object.
Typescript
const user = { name: 'Anna', active: true };
type UserType = typeof user;
This creates a type GreetType that is the type of the greet function.
Typescript
function greet() {
  return 'hello';
}
type GreetType = typeof greet;
Sample Program

This program uses typeof in type context to create ScoreType as the type of score. Then it uses this type for the function parameter to ensure only numbers like score are accepted.

Typescript
const score = 85;
type ScoreType = typeof score;

function printScore(s: ScoreType) {
  console.log(`Score is: ${s}`);
}

printScore(90);
OutputSuccess
Important Notes

Remember, typeof in type context works only in TypeScript, not in plain JavaScript.

Use typeof in type context with variables, constants, or functions.

Summary

typeof in type context gets the type of a variable or value.

It helps keep types consistent and avoid repetition.

Use it to create new types based on existing variables or functions.