ianstormtaylor / superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
https://docs.superstructjs.org
MIT License
6.96k stars 223 forks source link

Generate struct from TS interface #1173

Open aldo-roman opened 1 year ago

aldo-roman commented 1 year ago

Hi everyone I have some complex Typescript interfaces from a 3rd party library and I would like to use superstruct to validate at runtime.

Is there a way I can generate a superstruct schema from a Typescript interface?

eg


// user.ts
interface User {
  id: number
  name: string
}

/* Run some node command */

// output/superstruct-user.ts
const User = type({
  id: number(),
  name: string(),
})
JoniJnm commented 1 year ago

Sounds good idea. But I think it only can be done creating a typescript plugin. Similar than kimamula/ts-transformer-keys does

rvfakie commented 1 year ago

Wow it would be a nice feature. @ianstormtaylor is it possible to mark as a feature request?

shellscape commented 1 year ago

That would be a pretty heavy lift for this lib. While nice, it would involve walking a TypeScript AST, evaluating each node, and building a Node AST with something like acorn on the fly. As @JoniJnm mentioned, that would be better off a separate plugin.