Steve - I was wondering if there is a certain w...
I was wondering if there is a certain way to further optimize the
.refine
. And if possible, also improve the typing of it.
Basically also wondering I would be able to type TipTapTextDto['marks']
In a way that I define it to be an array of TipTapMarkDto
but also it to have at least one IdentifierMarkDto
, no matter the order in which the TipTapMarkDto
present themselves.
Solution:Jump to solution
You could use something like a brand to indicate to the consumer that it has been verified to contain a certain element, but the type system still wouldn't know how to encode that information, so you'd still have to code defensively
5 Replies
The first optimization of this is ofcourse rewriting it to this:
In a way that I define it to be an array of TipTapMarkDto but also it to have at least one IdentifierMarkDto, no matter the order in which the TipTapMarkDto present themselves.No 😅 . If you don't know exactly where it is (like first, or last, or third, etc) you cannot encode that invariant in the type itself. That's basically a feature of a dependent type system and TypeScript doesn't have a real dependent type system.
Solution
You could use something like a brand to indicate to the consumer that it has been verified to contain a certain element, but the type system still wouldn't know how to encode that information, so you'd still have to code defensively
😦 too bad
I guess one work around here is to use a combination of a runtime check with a branded type, and then write a function to extract the known value from the array that makes a type assertion. Or you can skip the branding and make a falliable function that will return the value if it exists or throw.