Typescript Foundations / Advanced Types

keyOf, typeOf, in

🔹 keyof – Get Keys of a Type

keyof is used to get a union of all property keys of a given type.

🔧 Syntax

type Person = {
  name: string;
  age: number;
};

type PersonKeys = keyof Person;
// "name" | "age"

💡 Use Case – Generic Functions

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const person = { name: "Tisha", age: 23 };
const age = getProperty(person, "age"); // ✅ works

🔸 typeof – Get Type from Value

typeof allows you to extract the type of a variable or object.

🔧 Syntax

let user = {
  name: "Aarav",
  age: 30,
};

type UserType = typeof user;
// same as: { name: string; age: number }

This is extremely useful when you want to base a type on a value without repeating yourself.

✅ Example with Function Return Type

function getUser() {
  return { name: "Priya", role: "admin" };
}

type ReturnTypeOfGetUser = ReturnType<typeof getUser>;

🔹 in – Create Mapped Types

The in keyword is used inside mapped types to iterate over keys.

🔧 Syntax

type Person = {
  name: string;
  age: number;
};

type OptionalPerson = {
  [K in keyof Person]?: Person[K];
};
// { name?: string; age?: number }

🛠 Use Case: Convert All Properties to Readonly

type ReadonlyPerson = {
  [K in keyof Person]: Readonly<Person[K]>;
};

🧠 Combine with keyof and typeof

const COLORS = {
  primary: "#ff0000",
  secondary: "#00ff00",
};

type ColorKeys = keyof typeof COLORS;
// "primary" | "secondary"


🧠 Summary Table

Keyword

Used For

Example

keyof

Get keys of a type as a union

keyof Person → `"name"

typeof

Get type of a variable or value

typeof user

in

Iterate over keys in mapped types

[K in keyof T]