ts-pattern
ts-pattern copied to clipboard
[Question] Possible to improve my match?
Hey, love this package a lot! Thank you.
I was wondering how I can improve on this check where a user may possible pass in an empty array, []. As it is optional and can be null I was hoping to just use P.not(P.nullish) but empty array's have ruined my party.
https://www.typescriptlang.org/play?target=99&module=1&pretty=true&allowSyntheticDefaultImports=true&ts=4.4.4#code/JYWwDg9gTgLgBAbziAhjAxgCwDRwApwC+cAZlBCHAEQwDOAtGGjAKZQB2VA3AFA-DtWUEinQs4AFRa14CHnDgooUFAE8A8uxYB+AFxwZUAQHMA2gF04AHzjsArgBsHvBUpWqJAdwh6DMI+xmljb2Ti6KymoSmFAsOvqGJhbWto7O8nAAJiwARnbG+jkQEA4sKOy8hHzoEOwycAJgdjD6UvUAvIgZbmqaLPoW2N2RHt76oQ5DriPRsf1wpjTSMFTmU1m5+fr+dixDhLw8NXXwwLQAouAwqnCdABRu+uWqySFpAJS3AHwRUHAAZP9fgA6UqBGCYOA-AAMh2O9UonVQGEwd0azXeGWBnmAELuSB6Gi0+jw2MwLHYdweyk+7R+AEIzpcwNdqVB3p9CLg0ewmjBaT85AoFLEYHYOA1ec1gYS+uFCJiFNjcaiCTMxvgyRSqW4BXBGRcrqo2RyiNz0fzvl1hXBReL2JK+TL1RB5Yq4Mq8Wr3LM4iStZSTVaDczWbrOeapZa6dbhXaJRbnT6YnE3cCIBC2DjaCwqXr4SUWKCIMY7gByEgsJxwCHkfKYMscuG1WiF4ulkDvLhAA
I want this to match the first non-empty String array and return just that array, to save me doing input.arrayOne. I can't seem to piece together the correct combination of P.array and P.select to get that to work.
Any ideas? Cheers.
Hey! I think you could use P.union and do something like this P.not(P.union([], null)) to check that your array is neither empty or null: Playground
@gvergnaud thank you so much, that's exactly what I had hoped for!
The only final place I have to break out of ts-pattern for these isEmpty checks from Lodash is when the object key has not been set, or if an empty object has been passed. Any ideas how to get this sandbox to print:
["test"]
{ test: true }
Appreciate this is an incredibly contrived example, but as it's API data want to be extra dilligent when matching on it. I am seeing if I can be lazy 😅