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?✗ Incorrect
keyof produces a union of the keys, so here it is 'a' | 'b'.Which of these is a valid use of
keyof?✗ Incorrect
keyof extracts keys from a type as a union of string literal types.If
type T = { x: number; y: number; }, what is keyof T?✗ Incorrect
keyof T is the union of the keys: 'x' | 'y'.What does
keyof any represent?✗ Incorrect
keyof any is the union of all possible key types: string | number | symbol.Can
keyof be used on primitive types like string?✗ Incorrect
Primitive types have wrapper objects with keys, so
keyof string returns keys like length.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.