#Run-time type validator?

6 messages · Page 1 of 1 (latest)

alpine oyster
#

Is there any easy way to generate runtime type validators for compile-time type objects? So for example, say I've got something like this:

interface User {
  id: string;
  first: string;
  last?: string;
  age?: number;
}

I can write a user-defined type guard that does what I want:

function isUser(obj: any): obj is User {
  return typeof obj == "object" 
    && obj != null
    && typeof obj.first == "string"
    && (obj.last === undefined || typeof obj.last == "string")
    && (obj.age === undefined || typeof obj.age == "number")
}

However, with a lot of types and a lot of properties this becomes a lot to maintain, and even worse there has to be manual syncing between the defined type User and the type-guard assertions in isUser(). This begs for automation, generating the isUser() and other methods.

sand briar
#

@alpine oyster It's better to use a library that has the runtime type validation and generate the type from it.

#

For example, with zod:

#
import z from "zod";
const UserSchema = z.object({
   id: z.string(),
   first: z.string(),
   last: z.string().optional(),
   age: z.number().optional()
})

type User = z.TypeOf<typeof UserSchema>
//   ^? - { id: string; first: string; last?: string | undefined; age?: number | undefined; }
unborn pastureBOT
sand briar
#

There's various other options other than zod out there, too but the idea is pretty much the same in all of them.