TypeScript · CODINGNEED
TypeScript unknown vs any: validate an API response
See why unknown protects an API boundary and why a type assertion cannot replace runtime validation.
हिन्दी में पढ़ें →The problem starts outside your program
Imagine an API is supposed to return a number of credits, but a broken integration returns "20" as text. Declaring that response as any lets the rest of your program call methods and read properties without a useful compiler objection. Declaring it unknown forces the next piece of code to prove what it received. Neither declaration changes the actual response.
Make the check match the business rule
If credits must be a nonnegative safe integer, a typeof check alone is incomplete. It accepts fractional numbers and values outside the integer range that JavaScript can represent exactly. Choose the whole contract and return a result the caller can handle.
function credits(value: unknown): number | null {
return typeof value === "number"
&& Number.isSafeInteger(value) && value >= 0
? value : null;
}
// credits(20) → 20
// credits("20") → null
// credits(-1) → nullAvoid silent conversions
Number(value) can be appropriate in a parser, but it is a different contract: an empty string and false convert to zero. If a user form accepts decimal text, write and test that parsing rule separately. Do not let a convenient conversion decide what your API accepts.
Test the boundary, then simplify the interior
Test zero, a positive integer, a fraction, a numeric string, null and a boolean. Once validation succeeds, pass the validated value deeper into the application with its known type. Keep error handling at the boundary. The check takes constant time and space for this scalar input; recursively validating a larger object depends on its size.
Official reference: TypeScript documentation
Continue exploring
- Why LEFT JOIN and COUNT(*) can report one order for a new customer
- Handle a retried API write without applying it twice
- ROW_NUMBER, RANK and DENSE_RANK: choose a tie policy
Suggest a correction: care@codingneed.com