vevcom / projectNext

Project Next is Omegas new website coming soon
MIT License
7 stars 0 forks source link

refactor: add satisfies keyword to config vars marked as const #215

Closed Paulijuz closed 4 months ago

Paulijuz commented 5 months ago

Found out that typescript has this neat little keyword satisfies. All it does is that it forces the left side of it to satisfy the type of the right side. Why is this useful? Well it works a bit like as const, as in it makes typescript narrow down the type of the value as much as possible, but with the benifit of having the ability to specify a type. For example, previously we had this array for which user fields to expose:

export const userFieldsToExpose = ['id', 'username', 'firstname', 'lastname', 'email', 'createdAt', 'updatedAt'] as const

The problem here is that if you misspell any of the fields you won't get an error here. You'll most likely catch the error if you try to use the array, but it would be nice to have an error straight away. In addition, you don't get intellisense autocomplete when you write in which fields you want to expose. The satisfies keywors solves this issue:

export const userFieldsToExpose = ['id', 'username', 'firstname', 'lastname', 'email', 'createdAt', 'updatedAt'] as const satisfies (keyof User)[]

Now we have explicitly marked that this array satisfies the type (keyof User)[]. Now typescript will check that the left side is an array of keys of the object type User. This also allowes intellisense to give hints for which fields you want to type.

The satisfies keyword especially becomes usefull for prisma input types. Now you can have autocomplete on you includers by doing something like this:

export const articleRealtionsIncluder = {
    articleSections: {
        include: articleSectionsRealtionsIncluder
    },
    coverImage: {
        include: {
            image: true
        },
    },
} as const satisfies Prisma.ArticleInclude

I have gone through the project and added the satisfies keyword with the proper type wherever I have seen an as const. I think this is something we should be doing from now on.