Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

3
  • I like the idea of strongly typed validation very much! This guarantees a minimal amount of validation without losing safety. Some questions/remarks: (1) You justly mention the use of brands to simulate nominal typing, as TypeScript uses structural typing. There are alternatives that don't have the (admittedly small) overhead of classes: see this post and here. (2) Is there a reason for returning an {error: string} object instead of throwing an exception? ... Commented May 15, 2022 at 10:04
  • 1
    (3) A practical question: you give an example of how this would work in NestJS with decorators. However, it seems that this approach doesn't have the benefits of strong typing, so I guess application logic in deeper layers might still accidentally perform unsafe operations. Do you know a way of combining both approaches? Commented May 15, 2022 at 10:06
  • 1
    @Safron (1) I don't see the class-based alternative, all of them use some variant of the brands pattern. (2) You can definitely use exceptions, but using error values might make it clearer that this operation is fallible and might make it easier to collect multiple validation errors. (3) You will not be able to create an object that is instanceof RegisterUserRequest and violates the validation constraints. This might be good enough. I am not aware of easy ways to combine NestJS validation with nominal typing. I'd expect that you'd need two separate types if you want to go this route. Commented May 15, 2022 at 11:19