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

combine type and object structs? #567

Open
ianstormtaylor opened this issue Dec 12, 2020 · 2 comments
Open

combine type and object structs? #567

ianstormtaylor opened this issue Dec 12, 2020 · 2 comments
Labels
✶ breaking Changes that would mean a breaking API change improvement

Comments

@ianstormtaylor
Copy link
Owner

Curious to hear other perspectives on this.

Right now the only difference between type and object struct is the "looseness" of the properties. type doesn't care about unknown properties, whereas object is "strict" and throws when unknown properties are received.

I was thinking it might make sense to just make type a subset of object that is accessed via a { loose: true } option:

const Nameable = object({
  first_name: string(),
  last_name: string(),
}, {
  loose: true
})

Might be easier to find/understand for new users.

@ianstormtaylor
Copy link
Owner Author

Could also allow layering in the masked utility as { mask: true } as well, since it only applies to objects.

When doing either of these we'd ensure that object structs can be passed as schemes to new object structs, so that you can immutably change the settings, for example:

const User = object({
  id: number(),
  name: string(),
})

const PermissiveUser = object(User, { loose: true, mask: true })

@ianstormtaylor ianstormtaylor added the ✶ breaking Changes that would mean a breaking API change label Feb 11, 2021
@VeryCrazyDog
Copy link

I use superstruct to validate configuration file. Sometimes someone might have a typo on the key field. I want the users to notice that mistake but I don't want to throw error and stop execution. So something like onExtraField will be useful.

const User = object({
  id: number(),
  name: string(),
  nickname: optional(string())
}, {
  // `onExtraField` is only valid when loose is `true`, so `onExtraField` is under `loose`
  loose: {
    onExtraField: fieldName => {
      console.log(`Unknown field '${fieldName}'`)
    }
  }
})

// Console output `Unknown field 'nicknmae'` without throwing error
User.assert({
  id: 1,
  name: 'Tony Stark',
  // Typo in the field name here
  nicknmae: 'Iron Man'
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✶ breaking Changes that would mean a breaking API change improvement
Projects
None yet
Development

No branches or pull requests

2 participants