Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active February 1, 2025 12:16
Show Gist options
  • Save rauschma/7f23068c0dd00bba3f59df955101e421 to your computer and use it in GitHub Desktop.
Save rauschma/7f23068c0dd00bba3f59df955101e421 to your computer and use it in GitHub Desktop.
assert-type: API for asserting types
// This code is now an npm package: https://github.com/rauschma/asserttt
@hcschuetz
Copy link

While it's cool to see how some type testing utils can be implemented in user code, I'd much prefer it to be provided by TypeScript itself. This could provide more helpful error messages than "Type 'false' does not satisfy the constraint 'true'." for code like this:

type _ = Assert<Equal<number, string>>;

(and we could probably omit the type _ = boilerplate). Furthermore the AssertEqual problem could probably be solved easily on that level.

And a minor remark on UnsupportedValueError. I see two primary error situations:

  1. Color gets an additional value, say Blue, but colorToString does not yet handle it. It is very nice that the constructor parameter of type never causes a compile-time error in this case (assuming that the tool chain does not just ignore type annotations).

  2. Some ill-typed code elsewhere invokes colorToString with an illegal argument, say "#ffffff". In this case a run-time error is actually thrown.

While the name UnsupportedValueError fits case 1, I'd suggest the name UnexpectedValueError, which would fit both cases.

@rauschma
Copy link
Author

@hcschuetz: Helpful, thanks!

While it's cool to see how some type testing utils can be implemented in user code, I'd much prefer it to be provided by TypeScript itself.

A agree! But it looks like the TypeScript team does not: microsoft/TypeScript#27024

While the name UnsupportedValueError fits case 1, I'd suggest the name UnexpectedValueError, which would fit both cases.

I was thinking of a switch over operating systems and someone passing in a value (=operating system) that is not supported. In a way, these three words all seem applicable: unsupported, illegal, unexpected.

“Unexpected” does seem like the best choice, because the term “illegal” has its own issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment