Challenge - 5 Problems
Keyof Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of keyof with interface keys
What is the output of the following TypeScript code when compiled and run in a JavaScript environment?
Typescript
interface Person {
name: string;
age: number;
location: string;
}
type PersonKeys = keyof Person;
const key: PersonKeys = "age";
console.log(key);Attempts:
2 left
💡 Hint
The keyof operator creates a union of the keys of the interface.
✗ Incorrect
The type PersonKeys is a union of the keys "name" | "age" | "location". Assigning "age" is valid and console.log prints "age".
🧠 Conceptual
intermediate1:30remaining
Understanding keyof with type aliases
Given the type alias below, what is the type of Keys?
Typescript
type Colors = {
red: string;
green: string;
blue: string;
};
type Keys = keyof Colors;Attempts:
2 left
💡 Hint
keyof creates a union of all keys in the type.
✗ Incorrect
keyof Colors produces a union of the keys "red", "green", and "blue".
❓ Predict Output
advanced2:30remaining
Output of keyof with union types
What is the output of this TypeScript code snippet when compiled and run?
Typescript
type A = { a: number };
type B = { b: string };
type AB = A | B;
type Keys = keyof AB;
const key1: Keys = "a";
const key2: Keys = "b";
console.log(key1, key2);Attempts:
2 left
💡 Hint
keyof on a union type produces the intersection of keys.
✗ Incorrect
keyof (A | B) is (keyof A) & (keyof B) = "a" & "b" = never. Assigning "a" to never causes a compilation error.
🔧 Debug
advanced2:00remaining
Identify the error with keyof and index signature
What error does this TypeScript code produce?
Typescript
type Dictionary = {
[key: string]: number;
};
type Keys = keyof Dictionary;
const key: Keys = 123;Attempts:
2 left
💡 Hint
keyof on a string index signature produces 'string'.
✗ Incorrect
keyof Dictionary where Dictionary = { [key: string]: number } is string. 123 has type number, which is not assignable to string.
📝 Syntax
expert3:00remaining
Which option causes a syntax error with keyof usage?
Which of the following TypeScript snippets will cause a syntax error?
Attempts:
2 left
💡 Hint
keyof expects an object type or union of object types, but more importantly, requires a type argument.
✗ Incorrect
keyof number is invalid because number is a primitive type, not an object type. This causes a syntax error. keyof on unions of object types or object literals is valid. keyof on tuple types like [number, string] is valid and produces keys like '0' | '1' | 'length' | etc. But D has no type after keyof, syntax error.