0
0
Typescriptprogramming~20 mins

Keyof operator in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Keyof Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
A"age"
BTypeError at runtime
C"location"
D"name"
Attempts:
2 left
💡 Hint
The keyof operator creates a union of the keys of the interface.
🧠 Conceptual
intermediate
1: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;
A"red" | "green" | "blue"
Bstring
Cnumber
Dnever
Attempts:
2 left
💡 Hint
keyof creates a union of all keys in the type.
Predict Output
advanced
2: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);
ATypeError at runtime
B"a b"
CCompilation error: Type '"a"' is not assignable to type 'never'
D"a a"
Attempts:
2 left
💡 Hint
keyof on a union type produces the intersection of keys.
🔧 Debug
advanced
2: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;
AType 'number' is not assignable to type 'never'
BType 'number' is not assignable to type 'string | number'
CNo error, code compiles fine
DType 'number' is not assignable to type 'string'
Attempts:
2 left
💡 Hint
keyof on a string index signature produces 'string'.
📝 Syntax
expert
3:00remaining
Which option causes a syntax error with keyof usage?
Which of the following TypeScript snippets will cause a syntax error?
Atype T = keyof (number | string);
Btype T = keyof;
Ctype T = keyof [number, string];
Dtype T = keyof {a: number, b: string};
Attempts:
2 left
💡 Hint
keyof expects an object type or union of object types, but more importantly, requires a type argument.