Skip to content

[Feature]: improved pure-JS definitions #213

@devlsh

Description

@devlsh

Description & Use case

currently defining schema in the pure-JS schema method can be not-so-flexible on typings - the simple prop: 'string', definitions are great and super simple to understand, but when you want to add typings to those strings (i.e. for enums), things start getting a little messy:

export const InventoryItemSchema = schema(
  {
    key: {
      type: 'string' as ItemKey,
    },
  },
  'InventoryItem',
);

not too bad, but still feels anti-pattern and against what the schema supports officially - things get more complicated/impossible when you want to do similar with a MapSchema:

export const InventorySchema = schema(
  {
    items: {
      map: InventoryItemSchema,
    },
  },
  'Inventory',
);

const inventory = new InventorySchema();

inventory.items.get('random-string-123')
inventory.items.get(itemKey.potion)

there is no way to type the key parameter for the underlying Map type, making it hard to do type-safe operations

name prop

the name prop as a second argument feels wrong, if that makes sense? just thought i'd add this in to the issue as it'd involve API changes already - might make sense to make it the first parameter and make it a required prop - keeps definitions structured and the API feeling natural to use

Optional: Proposed API

i think, given the pure-JS method is still pretty early, a slight change in API would make things more flexible and put it more on-par with modern type-safe ORMs like drizzle, i.e.

export const InventorySchema = schema('Inventory', {
  items1: map<typeof InventoryItemSchema, ItemKey>(InventoryItemSchema), // allows typing the Map `K`
  items2: map(InventoryItemSchema), // works like the current implementation, using `string`
  slots: number({ default: 3 }), // or `number().default(3),`
  anotherInt: int32(),
  somethingElse: array(SomeSchema),
  someEnum: string<MyEnumType>(),
});

under-the-hood, functionality remains the same - ultimately these are just helper methods that would provide better typing support and output the same structure that currently exists for schema() calls

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions