Forbid empty arrays

A bit more of type safety with array parameters.

Currently, the @Roles() decorator can be used with no arguments. This is because it accepts an array as parameter, so no arguments is like an empty array. That is not so interesting, as it should be used with at least one role. We can forbid this usage by creating a type for a non-empty array. This article further explains this process.

Then, let's create the file common -> util -> array.util and create our type there. Notice that it represents an array of type T, where the first item must be present, and then any amount of items after it is allowed, which enforces that at least one item should exist.

export type NonEmptyArray<T> = [T, ...T[]];

We then just need to go back to the roles.decorator file and set this type to the parameter.

...roles: NonEmptyArray<Role>

Commit - Empty arrays can now be forbidden

Last updated