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

assign breaks coercion #791

Open
pbarbiero opened this issue May 13, 2021 · 1 comment
Open

assign breaks coercion #791

pbarbiero opened this issue May 13, 2021 · 1 comment
Labels
bug ♥ help please Issues that we'd love help solving

Comments

@pbarbiero
Copy link

Wrapping a struct using defaulted with assign causes coercion to no longer work.

Easy enough test:

const struct = defaulted(
  object({
    id: string(),
    enabled: boolean(),
  }),
  {
    enabled: false,
  },
);

console.log(struct.coercer()); // { enabled: false }
console.log(assign(struct).coercer()); // undefined

Expected result: coercer still works

@ianstormtaylor ianstormtaylor added bug ♥ help please Issues that we'd love help solving labels May 18, 2021
@pbarbiero
Copy link
Author

@ianstormtaylor I am not a TS developer, and this is probably less elegant than you'd like, but this does resolve it for me:

// https://github.com/ianstormtaylor/superstruct/blob/main/src/structs/utilities.ts#L55
function assign(...Structs) {
  const isType = Structs[0].type === 'type';
  const schemas = Structs.map(s => s.schema);
  const coercers = Structs.map(s => s.coercer);
  const schema = Object.assign({}, ...schemas);
  const mergedSchema = isType ? type(schema) : object(schema);
  mergedSchema.coercer = (...args) => ({
    ...Object.assign({}, ...coercers.map(coercer => coercer(...args))),
  });
  return mergedSchema;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug ♥ help please Issues that we'd love help solving
Projects
None yet
Development

No branches or pull requests

2 participants