0
0
Typescriptprogramming~5 mins

Type assertions in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Astring as value
Bvalue as string
C<string>value as
Dvalue <as> string
What does a type assertion do at runtime?
ADoes nothing to the value
BPerforms a type check
CChanges the value's type
DThrows an error if types mismatch
Why might you avoid using angle-bracket type assertions in React (.tsx) files?
AThey are slower
BThey are deprecated
CThey conflict with JSX syntax
DThey cause runtime errors
If you assert a variable as a wrong type, what is the risk?
ACompiler will fix it automatically
BThe variable will change type at runtime
CCode will not compile
DRuntime errors may occur
Which of these is NOT a valid reason to use type assertions?
ATo convert a value's type at runtime
BTo work around incomplete type information
CTo tell the compiler a value has a more specific type
DTo access properties not in the inferred type
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.