Challenge - 5 Problems
Type Erasure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of generic function with type erasure
What is the output of this TypeScript code after compilation and running in JavaScript?
Typescript
function identity<T>(arg: T): T { return arg; } const result = identity<number>(42); console.log(typeof result);
Attempts:
2 left
💡 Hint
Remember that TypeScript types are removed during compilation.
✗ Incorrect
TypeScript removes all type information during compilation. The generic type T does not exist at runtime, so the typeof operator returns the JavaScript type of the value, which is "number".
🧠 Conceptual
intermediate2:00remaining
Effect of type erasure on runtime type checks
Which statement best describes the effect of TypeScript's type erasure on runtime type checks?
Attempts:
2 left
💡 Hint
Think about what happens to types after compilation.
✗ Incorrect
TypeScript removes all type annotations and interfaces during compilation, so no type information exists at runtime. Therefore, runtime type checks must be implemented manually if needed.
🔧 Debug
advanced3:00remaining
Why does this type guard fail at runtime?
Consider this TypeScript code snippet. Why does the type guard fail to distinguish types at runtime?
Typescript
interface Cat {
meow(): void;
}
interface Dog {
bark(): void;
}
function isCat(animal: Cat | Dog): animal is Cat {
return (animal as Cat).meow !== undefined;
}
const pet = { bark: () => console.log('woof') };
if (isCat(pet)) {
pet.meow();
} else {
pet.bark();
}Attempts:
2 left
💡 Hint
Check what happens to interfaces and type assertions at runtime.
✗ Incorrect
TypeScript interfaces do not exist at runtime. The type assertion does not add properties. The check relies on property presence, which can be unreliable if the object shape is not guaranteed.
📝 Syntax
advanced2:00remaining
Identify the runtime error caused by type erasure
What runtime error will this TypeScript code produce after compilation and running in JavaScript?
Typescript
function getLength<T>(arg: T): number { return arg.length; } console.log(getLength<string>("hello"));
Attempts:
2 left
💡 Hint
Consider what happens to the generic type and the argument passed.
✗ Incorrect
The generic type T is erased, but the argument is a string which has a length property. So accessing length works and outputs 5.
🚀 Application
expert3:00remaining
How to preserve type information at runtime despite type erasure?
Which approach allows you to preserve and use type information at runtime in TypeScript despite type erasure?
Attempts:
2 left
💡 Hint
Think about ways to add metadata manually or with tools.
✗ Incorrect
TypeScript erases types, but decorators and metadata reflection APIs can store type info explicitly for runtime use.