Extract type from or
Hello! Is it possible, using the following schema:
to extract one of the types ("find" it by the
intent
field)? I'd like to use it for multiple forms on a page.
It's possible to split it into multiple types, but having it in one type is more readable to me17 Replies
Yeah I'd say ideally you'd just want to define it as two types individually and then
.or
them together (usually best to start by defining any components you need to reuse rather than extract them out).
That said, there is an API just like TS for this:
Omg!!!!
Perfect, thanks!
I won't be reusing it at all, that's why I like to keep it as a single object
Where could I see an example of building such a helper in a type-safe way? (extracting the type by intent and omitting the intent key) Some test maybe?
My abominations end up with
never
This works! Sorry for butchering the library 🙈
It's not your fault, it's not possible for TS to statically compute that this is safe so you have to give up type safety inside an implementation like that to have it externally
Here's how I would write it though:
So much cleaner
Is it called function overloading when you declare the function name twice?
Well like I said I'm very used to having to cast constantly haha so may as well at least minimize the chaos 😛
Yeah in TS it works a lot like casting. Any of the declarations that are not on the implementation itself act as the external signature, then internally it very loosely asserts that they're correlated but it's basically a cast
I'd have two more questions 🙏
1. What is the
.as
function and
2. why when you cast as never
it still returns the proper valueCasting to
never
is just a way to allow an assignment, in this case from the return value to the statically declared type (Type<Omit<Extract<t, { intent: intent }>, "intent">>
)Mindblown, neber used it before. Will need to get used to this syntax
.as
is just a way to cast a type instance
Unfortunately it is not supported for arrow functions which are what I normally like to use
But it works well if you're already using function
Why do you use arrow functions? 👀 isn't it annoying to be able to use the function only under the declaration?
Not really, because that only applies if you're actually writing functions you're invoking at the top-level of the module instead of from other functions which is pretty rare.
It's mostly just a stylistic preference since they mirror the way functions are declared as types in TS
Makes a lot of sense!
Thank you for all these answers 🙏
No problem. Hopefully will be releasing
2.0.0-beta.7
this afternoon 🙏I'm rooting for you!