Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions .changeset/lazy-toes-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
"effect": patch
---

Made field-less `Schema.Struct({})` respect `onExcessProperty: 'ignore' | 'preseve' | 'error'`

Motivation: you remove one field, the resulting object gets fewer fields. You
remove another, fewer again. You remove the last; suddenly all the fields come
back, without respect to the default `onExcessProperty: "ignore"`. If the user
wanted to get all the fields, they have an option to set
`onExcessProperty: "preserve"`.

I tried attempting to defend old behavior with "`{}` means
`typeof obj === 'object' && obj !== null` and effect's schema tries to be
closer to typescript's behaviour, by treating `Schema.Struct({})` as something
passing the condition". And this might hold in isolation. But considering the
context, by this logic, any fields which are not explicitly mentioned in
`Schema.Struct({ ... })` should be preserved in all decoded objects, not only
the ones that have `{}` signature, to follow typescript's assignability rules.
And this is not what happens. The behavior should be consistent between
field-less structs and field-ful.

```ts
const arg = { hello: 'asd', redundant: 'asd' }
function fn(param: { hello: string }) {}
fn(arg)
```


New behavior

```ts
import * as Schema from 'effect/Schema'

const Something = Schema.Struct({})
const decodeSomething = Schema.decodeSync(Something);

const obj = { hello: 'stripped by default, unless asked otherwise' }

console.log(decodeSomething(obj))
// {}

console.log(decodeSomething(obj, { onExcessProperty: 'ignore' }))
// {}

console.log(decodeSomething(obj, { onExcessProperty: 'preserve' }))
// { hello: "stripped by default, unless asked otherwise" }

decodeSomething(obj, { onExcessProperty: 'error' })
// error: {}
// └─ ["hello"]
// └─ is unexpected, expected: never
```

Old behavior:

```ts
import * as Schema from 'effect/Schema'

const Something = Schema.Struct({})
const decodeSomething = Schema.decodeSync(Something);

const obj = { hello: 'stripped by default, unless asked otherwise' }

console.log(decodeSomething(obj))
// { hello: 'stripped by default, unless asked otherwise' }

console.log(decodeSomething(obj, { onExcessProperty: 'ignore' }))
// { hello: 'stripped by default, unless asked otherwise' }

console.log(decodeSomething(obj, { onExcessProperty: 'preserve' }))
// { hello: "stripped by default, unless asked otherwise" }

decodeSomething(obj, { onExcessProperty: 'error' })
// doesn't throw
```
36 changes: 35 additions & 1 deletion packages/effect/src/ParseResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1102,7 +1102,41 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => {
}
case "TypeLiteral": {
if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {
return fromRefinement(ast, Predicate.isNotNullable)
return (input, options) => {
if (!Predicate.isNotNullable(input)) {
return Either.left(new Type(ast, input))
}
if (Predicate.isRecord(input)) {
const onExcessPropertyError = options?.onExcessProperty === "error"
if (onExcessPropertyError) {
const reportAllErrors = options?.errors === "all"
const keys = Reflect.ownKeys(input)
const unexpectedPropertyIssues: Array<[number, ParseIssue]> = []
let stepKey = 0
for (const key of keys) {
const pointer = new Pointer(
key,
input,
new Unexpected(input[key], `is unexpected, expected: never`)
)
if (reportAllErrors) {
unexpectedPropertyIssues.push([stepKey++, pointer])
} else {
return Either.left(new Composite(ast, input, pointer, {}))
}
}
if (Arr.isNonEmptyArray(unexpectedPropertyIssues)) {
return Either.left(
new Composite(ast, input, sortByIndex(unexpectedPropertyIssues), {})
)
}
}
if (options?.onExcessProperty !== "preserve") {
return Either.right({})
}
}
return Either.right(input)
}
}

const propertySignatures: Array<readonly [Parser, AST.PropertySignature]> = []
Expand Down
2 changes: 1 addition & 1 deletion packages/effect/test/Schema/Schema/Record/Record.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ describe("record", () => {
it("Record(never, number)", async () => {
const schema = S.Record({ key: S.Never, value: S.Number })
await Util.assertions.decoding.succeed(schema, {})
await Util.assertions.decoding.succeed(schema, { a: 1 })
await Util.assertions.decoding.succeed(schema, { a: 1 }, {})
})

it("Record(string, number)", async () => {
Expand Down
26 changes: 24 additions & 2 deletions packages/effect/test/Schema/Schema/Struct/Struct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,25 @@ describe("Struct", () => {
it("empty", async () => {
const schema = S.Struct({})
await Util.assertions.decoding.succeed(schema, {})
await Util.assertions.decoding.succeed(schema, { a: 1 })
await Util.assertions.decoding.succeed(schema, { a: 1 }, {})
await Util.assertions.decoding.succeed(schema, [])

await Util.assertions.decoding.fail(
schema,
null,
`Expected {}, actual null`
)

await Util.assertions.decoding.fail(
schema,
{ a: 1 },
`{}
└─ ["a"]
└─ is unexpected, expected: never`,
{ parseOptions: Util.onExcessPropertyError }
)

await Util.assertions.decoding.succeed(schema, { a: 1 }, { a: 1 }, { parseOptions: Util.onExcessPropertyPreserve })
})

it("required property signature", async () => {
Expand Down Expand Up @@ -196,14 +207,25 @@ describe("Struct", () => {
it("empty", async () => {
const schema = S.Struct({})
await Util.assertions.encoding.succeed(schema, {}, {})
await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })
await Util.assertions.encoding.succeed(schema, { a: 1 }, {})
await Util.assertions.encoding.succeed(schema, [], [])

await Util.assertions.encoding.fail(
schema,
null as any,
`Expected {}, actual null`
)

await Util.assertions.encoding.fail(
schema,
{ a: 1 },
`{}
└─ ["a"]
└─ is unexpected, expected: never`,
{ parseOptions: Util.onExcessPropertyError }
)

await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 }, { parseOptions: Util.onExcessPropertyPreserve })
})

it("required property signature", async () => {
Expand Down