Recall & Review
beginner
What is a
type assertion in TypeScript?A type assertion tells the TypeScript compiler to treat a value as a specific type, overriding its inferred type without changing the runtime value.
Click to reveal answer
beginner
How do you write a type assertion using the
as syntax?You write the value followed by
as and the target type, like: value as TargetType.Click to reveal answer
intermediate
What is the difference between type assertion and type casting?
Type assertion only tells the compiler to treat a value as a certain type without changing the value at runtime, while type casting actually converts the value to a different type at runtime.
Click to reveal answer
intermediate
Can you use angle-bracket syntax for type assertions in TypeScript? When might it be discouraged?
Yes, you can write
<TargetType>value for type assertions. It is discouraged in .tsx files (React) because it conflicts with JSX syntax.Click to reveal answer
intermediate
What happens if you assert a type incorrectly in TypeScript?
The compiler trusts your assertion, so you might get runtime errors if the actual value does not match the asserted type. Type assertions do not perform checks.
Click to reveal answer
Which syntax is correct for asserting a variable
value as type string?✗ Incorrect
The correct syntax is
value as string.What does a type assertion do at runtime?
✗ Incorrect
Type assertions only affect the compiler, not the runtime value.
Why might you avoid using angle-bracket type assertions in React (.tsx) files?
✗ Incorrect
Angle-bracket assertions look like JSX tags and cause syntax errors in .tsx files.
If you assert a variable as a wrong type, what is the risk?
✗ Incorrect
Incorrect assertions can lead to runtime errors because the compiler trusts your assertion.
Which of these is NOT a valid reason to use type assertions?
✗ Incorrect
Type assertions do not convert types at runtime; they only affect compile-time checking.
Explain what a type assertion is and how it differs from type casting.
Think about what happens during compilation versus runtime.
You got /3 concepts.
Describe the two common syntaxes for type assertions in TypeScript and when to prefer one over the other.
Consider React files and JSX syntax.
You got /3 concepts.