0
0
Typescriptprogramming~5 mins

Custom type guard functions in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a custom type guard function in TypeScript?
A custom type guard function is a special function that checks if a value matches a specific type and tells TypeScript about this check, helping it understand the type better during code execution.
Click to reveal answer
beginner
How do you define a custom type guard function signature?
You define it with a return type using the syntax: <code>paramName is Type</code>. For example, <code>function isString(value: any): value is string</code> means the function returns true if <code>value</code> is a string.
Click to reveal answer
intermediate
Why use custom type guard functions instead of simple type checks?
Custom type guards help TypeScript narrow down types in complex situations, improving code safety and enabling better autocompletion and error checking.
Click to reveal answer
beginner
Example: What does this function do?<br><pre>function isNumber(value: any): value is number {<br>  return typeof value === 'number';<br>}</pre>
This function checks if the input value is a number. If yes, it returns true and tells TypeScript that value is a number from that point on.
Click to reveal answer
intermediate
How does TypeScript behave after a custom type guard returns true?
TypeScript narrows the type of the checked variable to the type specified in the guard, allowing safer access to properties or methods of that type.
Click to reveal answer
What is the correct return type for a custom type guard function checking if a value is a string?
Aboolean
Bstring
Cvalue is string
Dvalue: string
Which keyword is used inside a custom type guard function to check the type of a variable?
Atypeof or instanceof depending on the type
Binstanceof
Ctypeof and instanceof together
Dtypeof
What benefit does a custom type guard provide in TypeScript?
ARemoves the need for type annotations
BRuns faster code
CAutomatically converts types
DImproves type safety by narrowing types
Which of these is a valid custom type guard function signature?
Afunction isArray(value: any): boolean
Bfunction isArray(value: any): value is any[]
Cfunction isArray(value: any): any[]
Dfunction isArray(value: any): void
After a custom type guard returns true, what can you safely do with the variable?
AAccess properties or methods specific to the narrowed type
BAssign it to any type without error
CIgnore type checking
DUse it only as 'any' type
Explain what a custom type guard function is and how it helps TypeScript.
Think about how TypeScript understands variable types better after the guard.
You got /3 concepts.
    Write a simple custom type guard function that checks if a value is an array.
    Use Array.isArray to check the value inside the function.
    You got /3 concepts.