ianstormtaylor / superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
https://docs.superstructjs.org
MIT License
6.96k stars 223 forks source link

`defaulted` options not documented #1127

Open nhagen opened 1 year ago

nhagen commented 1 year ago

What is the intention of the strict option passable to defaulted?

The documentation for defaulted is pretty clear--it should only act on undefined(). But it also acts on plain objects that have undefined fields. This behavior is toggled according to the strict field on the options parameter.

What is the intention of the strict mode for defaulted? Why is it not true by default? What should users need to know about strict when using defaulted?

  it('should on default undefined values', () => {
    const TypeA = type({
      optionalField: optional(string())
    })

    const TypeB = type({
      someField: defaulted(TypeA, {optionalField: 'someValue'})
    })

    expect(create({}, TypeB).someField.optionalField).toBe('someValue')
    // somefield is not undefined, but a plain object with an undefined `someField` field.
    //
    // by default, `defaulted` acts on plain objects--not *only* undefined as described.
    // this is fixed by passing {strict: true} to the `defaulted` options param in the struct defintion
    // 
    expect(create({someField:{}}, TypeB).someField.optionalField).toBeUndefined() // fails
  })