Bird
Raised Fist0
Typescriptprogramming~10 mins

Runtime type checking strategies in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Runtime type checking strategies
Start: Receive input
↓
Check type at runtime
↓
Primitive
↓
Validate
↓
If valid: proceed
↓
If invalid: throw error or handle
↓
End
The program receives input, checks its type at runtime using different strategies for primitives, arrays, and objects, then proceeds if valid or handles errors if invalid.
Execution Sample
Typescript
function isString(value: any): boolean {
  return typeof value === 'string';
}

const input = "hello";
if (isString(input)) {
  console.log("Valid string");
}
This code checks if the input is a string at runtime and prints a message if it is.
Execution Table
StepActionInput ValueType Check ResultNext Step
1Receive input"hello"N/AProceed to type check
2Check if input is string"hello"truePrint 'Valid string'
3Print outputN/AN/AEnd execution
💡 Input passes the string type check, so execution ends after printing.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
inputundefined"hello""hello""hello"
isString(input)N/AN/Atruetrue
Key Moments - 2 Insights
Why do we need to check types at runtime if TypeScript already has types?
TypeScript types are erased at compile time, so runtime checks ensure the actual data matches expected types during execution, as shown in Step 2 of the execution_table.
What happens if the type check fails?
If the check returns false, the program should handle the error or reject the input. This is implied after Step 2 if the result was false, preventing further execution.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the type check result at Step 2?
Atrue
Bfalse
Cundefined
Dnull
💡 Hint
Check the 'Type Check Result' column in Step 2 of the execution_table.
At which step does the program print 'Valid string'?
AStep 1
BStep 2
CStep 3
DNo printing occurs
💡 Hint
Look at the 'Action' column for printing in the execution_table.
If the input was a number instead of a string, what would change in the execution_table?
AType Check Result at Step 2 would be false
BInput value at Step 1 would be 'true'
CProgram would print 'Valid string' anyway
DNo change in execution_table
💡 Hint
Refer to the 'Type Check Result' column and consider how type checking works.
Concept Snapshot
Runtime type checking in TypeScript:
- Use functions to check types at runtime (e.g., typeof, Array.isArray)
- Validate primitives, arrays, and objects differently
- Proceed if check passes, else handle errors
- Necessary because TypeScript types are erased at runtime
- Helps ensure data safety during execution
Full Transcript
This visual execution shows how runtime type checking works in TypeScript. The program starts by receiving input, then checks its type using a function like isString. If the input is a string, it prints a confirmation message. Variables like input and the result of isString are tracked step-by-step. Key moments include understanding why runtime checks are needed despite TypeScript's static typing and what happens if a check fails. The quizzes test understanding of the type check result, when output occurs, and how the table changes with different inputs.

Practice

(1/5)
1. Which of the following is the best way to check if a variable value is a string at runtime in TypeScript?
easy
A. Use value === String
B. Use value instanceof String
C. Use typeof value === 'string'
D. Use Array.isArray(value)

Solution

  1. Step 1: Understand the typeof operator

    The typeof operator returns a string indicating the type of the operand. For strings, it returns 'string'.
  2. Step 2: Compare with 'string'

    Checking typeof value === 'string' correctly verifies if value is a string primitive.
  3. Final Answer:

    Use typeof value === 'string' -> Option C
  4. Quick Check:

    typeof string = 'string' [OK]
Hint: Use typeof for primitives like string or number [OK]
Common Mistakes:
  • Using instanceof for string primitives
  • Confusing Array.isArray with string check
  • Comparing variable directly to String constructor
2. Which syntax correctly checks if a variable data is an array at runtime in TypeScript?
easy
A. Array.isArray(data)
B. data instanceof Array
C. typeof data === 'array'
D. data.constructor === 'Array'

Solution

  1. Step 1: Recall the standard array check method

    JavaScript and TypeScript provide Array.isArray() to check if a value is an array.
  2. Step 2: Verify the correct usage

    Calling Array.isArray(data) returns true if data is an array, false otherwise.
  3. Final Answer:

    Array.isArray(data) -> Option A
  4. Quick Check:

    Array.isArray([]) = true [OK]
Hint: Use Array.isArray() to check arrays safely [OK]
Common Mistakes:
  • Using typeof with 'array' (invalid)
  • Using instanceof which can fail across frames
  • Comparing constructor to string instead of function
3. What will be the output of this TypeScript code?
function isNumber(value: unknown): boolean {
  return typeof value === 'number';
}

console.log(isNumber('123'));
console.log(isNumber(123));
medium
A. false true
B. true true
C. true false
D. false false

Solution

  1. Step 1: Check typeof for '123'

    For the string '123', typeof '123' returns 'string', so isNumber('123') returns false.
  2. Step 2: Check typeof for 123

    For the number 123, typeof 123 returns 'number', so isNumber(123) returns true.
  3. Final Answer:

    false true -> Option A
  4. Quick Check:

    typeof '123' = string, typeof 123 = number [OK]
Hint: typeof returns 'number' only for number primitives [OK]
Common Mistakes:
  • Assuming string '123' is a number
  • Confusing typeof results
  • Ignoring return boolean values
4. Identify the error in this runtime type check function and fix it:
function isStringArray(value: unknown): boolean {
  return typeof value === 'string' && Array.isArray(value);
}
medium
A. No error, function is correct
B. Use Array.isArray(value) only, remove typeof check
C. Check should be typeof value === 'object' instead of 'string'
D. Check should be typeof value[0] === 'string' inside array

Solution

  1. Step 1: Analyze the current condition

    The function checks if value is both a string and an array, which is impossible.
  2. Step 2: Correct the logic for string arrays

    We should check if value is an array, then verify its elements are strings, e.g., typeof value[0] === 'string'.
  3. Final Answer:

    Check should be typeof value[0] === 'string' inside array -> Option D
  4. Quick Check:

    Array with string elements needs element type check [OK]
Hint: Check array type first, then element types inside [OK]
Common Mistakes:
  • Checking typeof array itself as 'string'
  • Ignoring element type checks
  • Assuming array is string without Array.isArray
5. You receive data of unknown type and want to safely check if it is an object with a numeric property id. Which runtime type checking strategy is best?
hard
A. Use Array.isArray(data) and check data.id
B. Check typeof data === 'object' and typeof data.id === 'number'
C. Check typeof data === 'string' and parse data.id
D. Use data instanceof Number to check id

Solution

  1. Step 1: Confirm data is an object

    Use typeof data === 'object' to ensure data is an object (and not null).
  2. Step 2: Check the property type

    Check typeof data.id === 'number' to confirm the id property is numeric.
  3. Final Answer:

    Check typeof data === 'object' and typeof data.id === 'number' -> Option B
  4. Quick Check:

    Object with numeric id needs both checks [OK]
Hint: Check object type then property type stepwise [OK]
Common Mistakes:
  • Using Array.isArray for objects
  • Checking string type for object
  • Using instanceof Number for primitives
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard