0
0
Typescriptprogramming~5 mins

Keyof operator in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the keyof operator do in TypeScript?
The keyof operator creates a union type of all the keys (property names) of a given object type.
Click to reveal answer
beginner
Given type Person = { name: string; age: number; }, what is keyof Person?
keyof Person is the union type 'name' | 'age', representing the keys of the Person type.
Click to reveal answer
intermediate
How can keyof help in writing safer functions?
Using keyof lets you restrict function parameters to only valid keys of an object, preventing errors from invalid property names.
Click to reveal answer
advanced
What is the result of keyof any in TypeScript?
keyof any is the union of string | number | symbol, because any object key can be one of these types.
Click to reveal answer
beginner
Can keyof be used with interfaces as well as types?
Yes, keyof works with both interfaces and type aliases to get the keys of the defined shape.
Click to reveal answer
What type does keyof { a: number; b: string; } produce?
Aobject
Bnumber | string
C'a' | 'b'
Dany
Which of these is a valid use of keyof?
ATo get the values of an object
BTo convert a type to a string
CTo create a new object
DTo get the keys of a type as a union
If type T = { x: number; y: number; }, what is keyof T?
A'x' | 'y'
Bnumber
Cobject
Dstring
What does keyof any represent?
Astring | number | symbol
Bany
Cobject
Dnever
Can keyof be used on primitive types like string?
ANo, it only works on objects
BYes, it returns keys of the wrapper object
CYes, but returns never
DNo, it causes an error
Explain what the keyof operator does and give an example.
Think about how you get property names from a type.
You got /3 concepts.
    How can using keyof improve type safety in functions?
    Consider how you can limit inputs to only existing keys.
    You got /3 concepts.