CodingNeed.

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) → null

Avoid 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

Suggest a correction: care@codingneed.com

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.