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

Mask with unions #803

Open
lvanhala opened this issue May 21, 2021 · 2 comments · May be fixed by #1196
Open

Mask with unions #803

lvanhala opened this issue May 21, 2021 · 2 comments · May be fixed by #1196

Comments

@lvanhala
Copy link

lvanhala commented May 21, 2021

Is there a way to make mask work with union? I'd like to define only one parser that I could use to:

  • Validate object and make sure it does not contain any extra fields
  • Parse object ignoring extra fields

I know I could use type() instead of object() but that would essentially require defining two parsers for the whole huge object tree.

Here's the minimal use case:

import { object, string, mask, literal, union } from 'superstruct'

const ItemA = object({
  type: literal('a'),
  valueA: string(),
})

const ItemB = object({
  type: literal('b'),
  valueB: string(),
})

// Works
mask(
  {
    type: 'a',
    valueA: 'test',
    extraField: true,
  },
  ItemA
)

// Fails
mask(
  {
    type: 'a',
    valueA: 'test',
    extraField: true,
  },
  union([ItemA, ItemB])
)

@dimikot
Copy link

dimikot commented Nov 29, 2023

@ianstormtaylor I believe the behavior mentioned above is actually a bugreport. Just prepared a failing test case for it independently, and then found the current issue reported:

  it.only('masking succeeds validation for objects with extra props in union', () => {
    const S = union([object({ a: string() }), object({ b: string() })])
    const value = { a: '1', extraProp: 42 }
    deepStrictEqual(mask(value, S), { a: '1' }) // fails!
  })

@dimikot
Copy link

dimikot commented Nov 29, 2023

@ianstormtaylor - I've just fixed it and submitted a PR here: #1196

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants