TypeScript's typeof operator

🌐

This post has been translated by DeepL . Please let us know if there are any mistranslations!

When using TypeScript, you'll often come across the typeof operator (which also exists in JavaScript). In TypeScript, typeof is used in two different contexts.

  1. JavaScript's runtime typeof operator
  2. Typeof as a type operator in TypeScript

1. JavaScript's runtime typeof operator

typeofreturns a string representing the data type of the operand.

let value = "hello";
console.log(typeof value); // "string"

let number = 32;
console.log(typeof number); // "number"

let func = () => {};
console.log(typeof func); // "function"

The returned values are JavaScript's basic data types (boolean, number, bigint, string, symbol, null, undefined) and function and object.

2. TypeScript's type operator typeof

In TypeScript, typeofcan also be used in the type context. In this case, the roles are different

const user = {
  name: "John",
  age: 30,
  isAdmin: true
};

const v_user = typeof user; // object
type User = typeof user;
// Result:
// type User = {
// name: string;
// age: number;
// isAdmin: boolean;
// }

In the example above, v_useris used in a variable declared with the const keyword. Therefore, it needs to be assigned a value, so it returns 'object', which indicates the runtime type of user. However, typeof, used after the type keyword, returns the type of the typescript.

Typeofshould only be used to extract a type from a value. If you use it on something that is already a type, you will get an error.

// Incorrect use
type MyString = string;
type Wrong = typeof MyString; // Error!

// Correct usage
const myString = "hello";
type Correct = typeof myString; // string

Utilizing typeof

1. extracting the union type from an array

const colors = ["red", "green", "blue"] as const;
type Colors = typeof colors[number];
// type Colors = "red" | "green" | "blue"

2. extract object type

// without as const
const config = {
  endpoint: "api.example.com",
  port: 3000
};
type Config = typeof config;
// type Config = {
// endpoint: string;
// port: number;
// }

// with as const
const config = {
  endpoint: "api.example.com",
  port: 3000
} as const;
type Config = typeof config;
// type Config = {
// readonly endpoint: "api.example.com";
// readonly port: 3000;
// }

When used withas const, readonlyis appended and extracted.

3. Extracting function types

You can extract the parameters and return type of a function by using the utility types ReturnType and Parameters.

function createUser(name: string, age: number) {
  return { id: Date.now(), name, age };
}

// return { type User = ReturnType<typeof createUser>;
// type User = {
// id: number;
// name: string;
// age: number;
// }

// type Param = Parameters<typeof createUser>
// type Param = {
// name: string;
// age: number;
// }

πŸ”Ž See also