Replies: 2 comments
-
Hi! That said, you can use a const hasOneKey = P.when((obj: {}) => Object.keys(obj).length === 1)
P.intersection(hasOneKey, { a: P.not(P.nullish) })
|
Beta Was this translation helpful? Give feedback.
0 replies
-
You could also create a "strictObject" pattern with function strictObject<Input, P extends P.Pattern<Input> & {}>(
pattern: P
): GuardExcludeP<Input, P.narrow<Input, P>, never> {
const patternKeys = new Set(Object.keys(pattern));
return P.when(
(value) =>
isMatching(pattern, value) &&
Object.keys(value).every((key) => patternKeys.has(key))
);
}
const result = match<{ a?: string; b?: string }>({ a: '', b: '' })
.with(strictObject({ a: P.string }), () => 'a')
.with(strictObject({ b: P.string }), () => 'b')
.otherwise(() => 'c')
expect(result).toBe('c'); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is there a way to match for 'property b should not exist'?
My usecase is, that I have an Object where all properties are optional and only one is allowed to be set at a time.
I know I could solve this with the ts-typesystem, but not in my case, as the object is coming from an API-Call.
What I already tried:
Given the Input Object
The pattern:
With what pattern can I say 'match if a is there, but no other property`?
Beta Was this translation helpful? Give feedback.
All reactions