jkomoros / card-web

The web app behind thecompendium.cards
Apache License 2.0
46 stars 8 forks source link

Use ZodTypes instead of type_constants.ts #673

Open jkomoros opened 8 months ago

jkomoros commented 8 months ago

Currently a lot of enum types are created by having a pattern like this:

//type_contstants.ts
export const BEFORE_FILTER_NAME = 'before';
export const AFTER_FILTER_NAME = 'after';
export const BETWEEN_FILTER_NAME = 'between';

export const DATE_RANGE_TYPES = {
    [BEFORE_FILTER_NAME]: true,
    [AFTER_FILTER_NAME]: true,
    [BETWEEN_FILTER_NAME]: true,
};

//types.ts
export type DateRange = keyof typeof DATE_RANGE_TYPES

This is a smaller example; there are a dozen and most are much longer. There's a whole lot of constant duplication and imports.

But this pattern predates using Typescript, and actually in most places where you have a tight typescript type it will complain if you have an incorrect type anyway, so we could get rid of a lot of unnecessary indirection.

The main thing to watch out for is there are a few places where a tighter enum is used in a string field. There you'd want to make an explicit const with the tighter type to verify and typecheck, and then use the const in the broader field.

Using Zod to drive the enum will make it possible to iterate through the various legal values easily, instead of doing a weird indirection of having an object with each key.

Noticed while working on #670.