nvie/decoders

Decoder creates object property with undefined value

w01fgang opened this issue · 3 comments

The actual behavior

const decoder = object({
    id: number,
    name: string,
    address: optional(string),
});
decoder({ id: 1, name: "test" }).unwrap();
// returns this
{ id: 1, name: "test", address: undefined };

Expected behavior

const decoder = object({
    id: number,
    name: string,
    address: optional(string),
});
decoder({ id: 1, name: "test" }).unwrap();
// returns this
{ id: 1, name: "test" };

Why it matters?

type Params = {|
  host?: string,
  port?: number,
|};
const decoder = exact({
  host: optional(string),
  port: optional(number),
});
const validate = guard(decoder);
const params = validate({});
const options = {
  host: "localhost",
  port: 3000,
  ...params,
};
console.log(options);
/*
{
  host: undefined,
  port: undefined
}
*/

Workaround

const decoder = exact({
  host: optional(string),
  port: optional(number),
});
const validate = guard(decoder);
const params = JSON.parse(JSON.stringify(validate({})));
console.log(params);
/*
{}
*/
nvie commented

Hi @w01fgang — thanks for reporting this! I've made a PR for this, and added some test cases to express the new behavior. I'll need to give this a pass over some real world code bases before I merge this in, because I want to make sure I don't break any behavior that is implicitly relied upon.

Hi @nvie, thanks a lot!
decoders are great, thank you for creating and sharing them!

nvie commented

Thanks @w01fgang – I just released this as v1.23.3 🙏