0
0
Typescriptprogramming~5 mins

Literal types and value narrowing in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a literal type in TypeScript?
A literal type is a type that represents a specific fixed value, like a string literal "hello" or a number literal 42, instead of a general type like string or number.
Click to reveal answer
beginner
How does TypeScript narrow types using literal types?
TypeScript narrows types by checking values against literal types in conditions, so inside an if statement checking for a specific literal, the type becomes that literal type.
Click to reveal answer
beginner
What will be the type of variable 'x' after this check?<br>
if (x === "open") { /* here */ }
Inside the if block, 'x' is narrowed to the literal type "open" because the condition ensures 'x' equals that exact string.
Click to reveal answer
intermediate
Why are literal types useful in function parameters?
Literal types let you restrict function parameters to specific allowed values, helping catch errors early and making code easier to understand.
Click to reveal answer
intermediate
Explain how union types and literal types work together for narrowing.
When a variable has a union of literal types, TypeScript can narrow it to one specific literal inside conditional checks, allowing precise control over possible values.
Click to reveal answer
What type does TypeScript assign to a variable declared as const status = "success";?
Aunknown
Bstring
Cany
D"success" (literal type)
Given let mode: "auto" | "manual";, what happens inside if (mode === "auto") block?
Amode is narrowed to "auto"
Bmode remains "auto" | "manual"
Cmode is any
Dmode is string
Which of these is NOT a literal type in TypeScript?
A"hello"
B42
Cboolean
Dtrue
How does TypeScript treat a variable declared as let x = 10; without a type annotation?
Ax has type number
Bx has type 10 (literal)
Cx has type any
Dx has type unknown
What is the benefit of using literal types in TypeScript?
AThey convert types to any
BThey allow precise control over allowed values
CThey disable type checking
DThey make variables mutable
Describe what literal types are and how TypeScript uses them to narrow values in code.
Think about how checking a variable against a specific value changes its type.
You got /3 concepts.
    Explain how union types combined with literal types help in writing safer TypeScript functions.
    Consider how limiting inputs to specific values prevents errors.
    You got /3 concepts.