A minimal, fast, intuitive, and customisable type-checking helper that you are missing.

I use io-ts to get both TypeScript and runtime types.

Define your schemas:

const StudentSchema = t.type({
  id: t.number,
  name: t.string

const UniversitySchema = t.type({
  students: t.array(StudentSchema),
  isNotAScam: t.boolean,

Extract the types from said schema:

type University = t.Typeof<typeof UniversitySchema>;

Use that shit to help you code:

const trumpUniversity: University = { students: [] }
// ^ Compile time error! Missing `isNotAScam`!

Or to validate some unknown user input:

const isARealBoy = isRight(StudentSchema.decode(someUserInputJson));
if (!isARealBoy) bitchAtTheUser();

I find it intuitive. It also supports generics and other fancy features. (Which I find less intuitive, but them’s the rules — if you want advanced stuff you need advanced understanding.)

Now go forth and make dope compile/runtime checked JS.

Author: admin

Leave a Reply

Your email address will not be published.