Menu

unknown does not validate an API response: comparing any, assertions, and runtime checks
📰

unknown does not validate an API response: comparing any, assertions, and runtime checks

DEV Community: typescript·hiro@·3 days ago
#x6SpplJk
#devtotypescript#devto#dev#value#ticket
Long article (821 words) — no AI summary yet.
Reading 0:00
15s threshold

Receiving an external API response as unknown lets the compiler stop property access that has not been checked. The type itself does not validate the shape of JSON at runtime.

This comparison uses a push sender from a personal project to test any, unknown, and type assertions. Comparing compiler results with runtime logs also found malformed responses that the code silently skipped.

Change only the type for the same JSON

In the following value, data is not an array.

const raw = '{"data":{"unexpected":true}}' ; const value : any = JSON . parse ( raw ) ; console . log ( value . data [ 0 ] . status . toUpperCase ( ) ) ;

Enter fullscreen mode

Exit fullscreen mode

Verification used macOS 26.6.2, Node.js 24.15.0, and TypeScript 7.0.2. Compiler settings were strict, target ES2022, and noEmit.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.