JS20

Documentation

JS20 - Documentation

Schemas

Schemas are used to verify your data structures at runtime.

import { sBoolean, sDate, sInteger, sNumber, sString } from '@js20/schema';

export interface Something {
    text: string;
    optional?: number;
    isEnabled: boolean;
    anInteger: number;
    aDate: Date;
    withRegex: string;
}

// Make sure to extend the TS type!
export const sSomething: Something = {
    text: sString().maxLength(200).type(),
    optional: sNumber().optional().type(),
    isEnabled: sBoolean().type(),
    anInteger: sInteger().min(0).max(1).type(),
    aDate: sDate().type(),
    withRegex: sString().matches(/^[a-z]+$/).type(),
};

What's happening here?

  • A schema is an interface but for runtime. You can also add additional rules like min(), max(), matches() etc.
  • By having the schema extend the interface we get type safety and autocompletion in our IDE
  • All schema field has to end with type() to cast it into the expected type
  • Use optional() for optional fields
  • We recommend to use s<YourInterfaceName> as naming
JS20