Thuta Learning
TypeScript
AdvancedProgrammingintermediate

Async APIs, Errors & Runtime Validation

TypeScriptLesson 22

What you'll walk away with

  • Explain the runtime-value and compile-time-type relationship in Async APIs, Errors & Runtime Validation
  • Test unsafe input and edge cases in strict mode
  • Write maintainable TypeScript contracts

Build Async APIs, Errors & Runtime Validation as a system involving module resolution, runtime validation, declaration output, incremental builds, CI, and package boundaries—not only a compiler concern. Remember that TypeScript types are erased at runtime.

Build a Complete Mental Model

Build Async APIs, Errors & Runtime Validation as a system involving module resolution, runtime validation, declaration output, incremental builds, CI, and package boundaries—not only a compiler concern. Remember that TypeScript types are erased at runtime.

Apply It in Production TypeScript

Type-check an original Async APIs, Errors & Runtime Validation example in strict mode, then test valid values, null/undefined, malformed API data, a new union variant, and module boundaries. Fix the contract or validation instead of silencing errors with assertions or any.

After This Lesson

typescript
type User = { id: string; name: string };

function isUser(value: unknown): value is User {
  if (typeof value !== 'object' || value === null) return false;
  const record = value as Record<string, unknown>;
  return typeof record.id === 'string' && typeof record.name === 'string';
}

async function loadUser(): Promise<User> {
  const value: unknown = await fetch('/api/user').then(r => r.json());
  if (!isUser(value)) throw new Error('Invalid user response');
  return value;
}
You should see
Untrusted JSON is validated before becoming User.

Try It Yourself

Type-check an original Async APIs, Errors & Runtime Validation example in strict mode, then test valid values, null/undefined, malformed API data, a new union variant, and module boundaries. Fix the contract or validation instead of silencing errors with assertions or any.

Type Safety Warning

Assuming a successful TypeScript compile proves API data and runtime behavior are valid.

NarrowingTypeScript

Easy traps

  • Assuming a successful TypeScript compile proves API data and runtime behavior are valid.
  • Silencing an error with any, as, or a non-null assertion instead of repairing the contract.

Hands-on Exercise

Type-check an original Async APIs, Errors & Runtime Validation example in strict mode, then test valid values, null/undefined, malformed API data, a new union variant, and module boundaries. Fix the contract or validation instead of silencing errors with assertions or any.

You'll know it worked when: Untrusted JSON is validated before becoming User.