Sometimes, we want to check the type of data while the program is running to avoid errors. This helps make sure the program works correctly with the right kind of data.
Runtime type checking strategies in Typescript
if (typeof variable === 'string') { // code for string } else if (typeof variable === 'number') { // code for number } else { // code for other types }
Use typeof to check simple types like string, number, boolean.
For objects or arrays, use Array.isArray() or check properties manually.
value is a string before using it.const value: unknown = 'hello'; if (typeof value === 'string') { console.log('It is a string:', value); } else { console.log('Not a string'); }
function isNumber(value: unknown): value is number { return typeof value === 'number'; } const input: unknown = 42; if (isNumber(input)) { console.log('Number:', input); } else { console.log('Not a number'); }
data is an array before using array methods.const data: unknown = [1, 2, 3]; if (Array.isArray(data)) { console.log('It is an array with length:', data.length); } else { console.log('Not an array'); }
This program checks the type of different values at runtime and prints a message based on the type.
function checkType(value: unknown) { if (typeof value === 'string') { console.log(`String with length ${value.length}`); } else if (typeof value === 'number') { console.log(`Number with value ${value}`); } else if (Array.isArray(value)) { console.log(`Array with ${value.length} items`); } else { console.log('Unknown type'); } } checkType('hello'); checkType(123); checkType([1, 2, 3]); checkType({});
Runtime checks add safety but can slow down the program if overused.
TypeScript types disappear when running the program, so runtime checks are needed for real-time safety.
Use custom type guard functions to keep code clean and reusable.
Runtime type checking helps catch wrong data types while the program runs.
Use typeof, Array.isArray(), and custom functions for checks.
It is useful when working with unknown or dynamic data sources.
Practice
value is a string at runtime in TypeScript?Solution
Step 1: Understand the typeof operator
Thetypeofoperator returns a string indicating the type of the operand. For strings, it returns 'string'.Step 2: Compare with 'string'
Checkingtypeof value === 'string'correctly verifies ifvalueis a string primitive.Final Answer:
Usetypeof value === 'string'-> Option CQuick Check:
typeof string = 'string' [OK]
- Using instanceof for string primitives
- Confusing Array.isArray with string check
- Comparing variable directly to String constructor
data is an array at runtime in TypeScript?Solution
Step 1: Recall the standard array check method
JavaScript and TypeScript provideArray.isArray()to check if a value is an array.Step 2: Verify the correct usage
CallingArray.isArray(data)returns true ifdatais an array, false otherwise.Final Answer:
Array.isArray(data) -> Option AQuick Check:
Array.isArray([]) = true [OK]
- Using typeof with 'array' (invalid)
- Using instanceof which can fail across frames
- Comparing constructor to string instead of function
function isNumber(value: unknown): boolean {
return typeof value === 'number';
}
console.log(isNumber('123'));
console.log(isNumber(123));Solution
Step 1: Check typeof for '123'
For the string '123',typeof '123'returns 'string', soisNumber('123')returns false.Step 2: Check typeof for 123
For the number 123,typeof 123returns 'number', soisNumber(123)returns true.Final Answer:
false true -> Option AQuick Check:
typeof '123' = string, typeof 123 = number [OK]
- Assuming string '123' is a number
- Confusing typeof results
- Ignoring return boolean values
function isStringArray(value: unknown): boolean {
return typeof value === 'string' && Array.isArray(value);
}Solution
Step 1: Analyze the current condition
The function checks ifvalueis both a string and an array, which is impossible.Step 2: Correct the logic for string arrays
We should check ifvalueis an array, then verify its elements are strings, e.g.,typeof value[0] === 'string'.Final Answer:
Check should betypeof value[0] === 'string'inside array -> Option DQuick Check:
Array with string elements needs element type check [OK]
- Checking typeof array itself as 'string'
- Ignoring element type checks
- Assuming array is string without Array.isArray
id. Which runtime type checking strategy is best?Solution
Step 1: Confirm data is an object
Usetypeof data === 'object'to ensuredatais an object (and not null).Step 2: Check the property type
Checktypeof data.id === 'number'to confirm theidproperty is numeric.Final Answer:
Checktypeof data === 'object'andtypeof data.id === 'number'-> Option BQuick Check:
Object with numeric id needs both checks [OK]
- Using Array.isArray for objects
- Checking string type for object
- Using instanceof Number for primitives
Ready to prove it?
Pass the test and this pattern moves unknown
