bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/TypeScript/TypeScript Core
TypeScript•TypeScript Core

TypeScript Keyof

keyof is a keyword in TypeScript which is used to extract the key type from an object type.

keyof with explicit keys

When used on an object type with explicit keys, keyof creates a union type with those keys.

Example

interface Person {
  name: string;
  age: number;
}
// `keyof Person` here creates a union type of "name" and "age", other strings will not be allowed function printPersonProperty(person: Person, property: keyof Person) { console.log(`Printing person property ${property}: "${person[property]}"`);
}
let person = {
  name: "Max", age: 27
};
printPersonProperty(person, "name"); // Printing person property name: "Max"

keyof with index signatures

keyof can also be used with index signatures to extract the index type.

Example

type StringMap = { [key: string]: unknown };
// `keyof StringMap` resolves to `string` here function createStringPair(property: keyof StringMap, value: string): StringMap {
return { [property]: value };
}

Previous

TypeScript Utility Types

Next

TypeScript Null & Undefined

This chapter

Overview
40

Lessons

241m

Read time

1. TypeScript Tutorial2. TypeScript Introduction3. TypeScript Getting Started4. TypeScript Simple Types5. TypeScript Explicit Types and Inference6. TypeScript Special Types7. TypeScript Arrays8. TypeScript Tuples9. TypeScript Object Types10. TypeScript Enums11. TypeScript Type Aliases and Interfaces12. TypeScript Union Types13. TypeScript Functions14. TypeScript Casting15. TypeScript Classes16. TypeScript Basic Generics17. TypeScript Utility Types18. TypeScript Keyof19. TypeScript Null & Undefined20. TypeScript Definitely Typed21. TypeScript 5.x Updates22. TypeScript Configuration23. TypeScript with Node.js24. TypeScript with React25. TypeScript Tooling26. TypeScript Advanced Types27. TypeScript Type Guards28. TypeScript Conditional Types29. TypeScript Mapped Types30. TypeScript Type Inference31. TypeScript Literal Types32. TypeScript Namespaces33. TypeScript Index Signatures34. TypeScript Declaration Merging35. TypeScript Async Programming36. TypeScript Decorators37. TypeScript in JavaScript Projects (JSDoc)38. TypeScript Migration Guide39. TypeScript Error Handling40. TypeScript Best Practices

On this page

keyof with explicit keyskeyof with index signatures