Sobes.tech
Middle

What are keyof and typeof in TypeScript?

sobes.tech AI

Answer from AI

keyof and typeof are key operators in TypeScript for working with types.

  • keyof is an operator that returns a union of string literals representing the property names of an object or interface. For example, if there is an interface:
interface User {
  id: number;
  name: string;
}

type UserKeys = keyof User; // "id" | "name"
  • typeof in the context of types is used to obtain the type of a variable or object. This is different from the JavaScript typeof operator, which returns a string with the type of the value. In TypeScript, typeof allows you to take the type of an existing variable:
const user = { id: 1, name: "Alice" };
type UserType = typeof user; // { id: number; name: string; }

Thus, keyof helps to get the keys of a type, and typeof — the type of an existing variable or object.