Strongly type third-party integrations with TypeScript

Markus Tacker

Markus Tacker

Pronouns: he/him

Principal R&D Engineer
Nordic Semiconductor
Trondheim, Norway

coderbyheart.com/socials

Book club: REST in Practice

https://restinpractice.com/

https://coderbyheart.com/rest-in-practice-reading-guide

Needs

  • Validate incoming data
  • Validate outgoing data
  • TypeScript
  • Third-party endpoint (we cannot use gRPC/tRPC)

Why JSON schema

  • Good enough
  • Widely known syntax for defining validations
  • Can easily be ported to other implementations
  • Can be adopted / read by other teams using other languages

Solution: @sinclair/typebox

  • JSON Schema based
  • In-memory validation
  • Fast TypeCompiler (~2x faster than AJV)

Validation basics

Code demo: code/validator/validateWithTypeBox.ts

Best practices

  • Re-use and compose
  • Add titles, descriptions
  • Keep schema open (allow additional properties)

validatingFetch() for JSX

  • handle async validation
  • nicer syntax

https://github.com/hello-nrfcloud/web/blob/926fb672bdb5fbad5fe1a04f244355d50e3cb5ee/src/utils/validatingFetch.ts#L42

Code demo: code/preact/SIMUsageHistory.tsx

Code organization

Discussion

Alternatives?

Thank you

Please share your feedback!

coderbyheart.com/socials

Latest version:
coderbyheart.com/talks