Challenge - 5 Problems
Union vs Intersection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of union type variable assignment
What will be the output of the following TypeScript code?
Typescript
type A = { name: string } | { age: number };
const person: A = { name: "Alice", age: 30 };
console.log(person);Attempts:
2 left
💡 Hint
For union types of object shapes, object literals must match exactly one member without excess properties due to TypeScript's excess property checking.
✗ Incorrect
The union type requires the object to match either { name: string } or { age: number } exactly. The literal has excess 'age' for the first and excess 'name' for the second, causing a TypeScript compilation error due to excess property checking.
❓ Predict Output
intermediate2:00remaining
Output of intersection type variable assignment
What will be the output of this TypeScript code?
Typescript
type B = { name: string } & { age: number };
const person: B = { name: "Bob", age: 25 };
console.log(person);Attempts:
2 left
💡 Hint
Intersection means the object must have all properties from both types.
✗ Incorrect
The intersection type requires the object to have both name and age properties. The object literal satisfies this, so it prints the full object.
🧠 Conceptual
advanced1:30remaining
Understanding union vs intersection types
Which statement best describes the difference between union and intersection types in TypeScript?
Attempts:
2 left
💡 Hint
Think about whether the value needs to meet one or all conditions.
✗ Incorrect
Union types mean the value can be one of several types. Intersection types mean the value must satisfy all types at once.
❓ Predict Output
advanced2:30remaining
Output of function with union and intersection parameters
What is the output of this TypeScript code?
Typescript
type X = { a: number } | { b: string };
type Y = { a: number } & { b: string };
function testUnion(x: X) {
if ('a' in x) return x.a;
return x.b.length;
}
function testIntersection(y: Y) {
return y.a + y.b.length;
}
console.log(testUnion({ a: 10 }));
console.log(testUnion({ b: "hello" }));
console.log(testIntersection({ a: 5, b: "world" }));Attempts:
2 left
💡 Hint
Check how the functions handle union and intersection types differently.
✗ Incorrect
testUnion checks which property exists and returns accordingly. testIntersection requires both properties and sums them. The outputs are 10, 5, and 10 respectively.
🔧 Debug
expert2:00remaining
Why does this intersection type assignment fail?
Why does the following TypeScript code produce an error?
Typescript
type C = { x: number } & { y: number };
const obj: C = { x: 1 };
Attempts:
2 left
💡 Hint
Think about what intersection means for required properties.
✗ Incorrect
Intersection types require all properties from all types. obj is missing 'y', so assignment fails.