TypeScript checks relationships in code that has already been typed. It does not validate JSON from a browser, database driver, queue, or external service at runtime. Boundary code should turn unknown input into a trusted internal value through parsing or a guard.
Put runtime checks where trust changes
Accept
unknownAvoid
anyEnforce architectural ownership
Place shared API contracts in the package or module that owns them. Import direction rules can stop UI code from depending on server internals and prevent shared packages from importing an app. Keep types close to behavior when they are not truly shared; exporting every interface creates a second public API to maintain.
Run strict type checking and boundary linting in CI. Add runtime tests for invalid payloads because compile-time tests cannot prove that external data is valid. A type system is most useful when it describes verified facts, not assumptions that crossed a boundary unchecked.
Validate the boundary before using the inferred type
The TypeScript narrowing handbook describes how control flow and runtime checks let the compiler refine a broad type. Network JSON still starts as data from outside the process. A type annotation or assertion does not run any checks on that value. Parse it as unknown and validate the structure needed for the operation. TypeScript narrowing handbook
A realistic example is a blog ID arriving in both a URL and an API body. A syntactically valid string can identify someone else's article. Check the field's form first, then use the current actor and article ID in a server-side authorization check. Add one test for malformed input and another for a well-formed ID belonging to a different account. The two tests catch different mistakes and should produce deliberate responses.
Worked example
A TypeScript type guard narrows runtime input after validation. It does not establish ownership; load the record and authorize it separately before returning private content.
tsfunction isArticleId(value: unknown): value is string { return typeof value === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(value); }




Community
Discussion
Loading comments…