Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add strictObject decoder #58

Closed
wants to merge 1 commit into from
Closed

add strictObject decoder #58

wants to merge 1 commit into from

Conversation

mrjones2014
Copy link

@mrjones2014 mrjones2014 commented Feb 18, 2021

This PR addresses #57 and adds a strictObject decoder. This decoder is much like the object decoder, with the additional behavior of returning an error if the decoded object has extra keys that were not defined on the decoder.

Fixes #57

@@ -293,6 +293,43 @@ export class Decoder<A> {
});
}

static strictObject<A>(decoders?: DecoderObject<A>) {
const decoderKeys = isJsonObject(decoders) ? Object.keys(decoders) : [];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need to decode decoders do we? Can just be

const decoderKeys = decoders ? Object.keys(decoders) : [];

Can we make decoders a required field? Then it would be even simpler:

const decoderKeys = Object.keys(decoders);

Comment on lines +298 to +305
return new Decoder((json: unknown) => {
const invalidKeys = isJsonObject(json)
? Object.keys(json).filter((key: string) => !decoderKeys.some((validKey: string) => key === validKey))
: [];

if (invalidKeys.length > 0) {
return Result.err({message: `the following keys are present but not expected: ${invalidKeys.join(", ")}`});
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it might be better to represent this decoder as the intersection of the standard object decoder and another no extra keys decoder. Avoid copying the contents of that decoder into this one.

@mojotech mojotech deleted a comment from widmar Feb 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

object decoder should have an option to throw error if extra properties are present
2 participants