Skip to content

Commit

Permalink
Allow frozen objects/arrays to be coerced (ianstormtaylor#1151)
Browse files Browse the repository at this point in the history
* Update tuple coercer
* Update record coercer
* Add frozen objects/arrays tests
  • Loading branch information
arturmuller committed Nov 3, 2023
1 parent 03d65bd commit 23787ae
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/structs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,9 @@ export function record<K extends string, V>(
isObject(value) || `Expected an object, but received: ${print(value)}`
)
},
coercer(value) {
return isObject(value) ? { ...value } : value
},
})
}

Expand Down Expand Up @@ -453,6 +456,9 @@ export function tuple<A extends AnyStruct, B extends AnyStruct[]>(
`Expected an array, but received: ${print(value)}`
)
},
coercer(value) {
return Array.isArray(value) ? value.slice() : value
},
})
}

Expand Down
9 changes: 9 additions & 0 deletions test/validation/array/valid-frozen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { array, number } from '../../../src'

export const Struct = array(number())

export const data = Object.freeze([1, 2, 3])

export const output = [1, 2, 3]

export const create = true
18 changes: 18 additions & 0 deletions test/validation/object/valid-frozen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { object, string, number } from '../../../src'

export const Struct = object({
name: string(),
age: number(),
})

export const data = Object.freeze({
name: 'john',
age: 42,
})

export const output = {
name: 'john',
age: 42,
}

export const create = true
15 changes: 15 additions & 0 deletions test/validation/record/valid-frozen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { record, string, number } from '../../../src'

export const Struct = record(string(), number())

export const data = Object.freeze({
a: 1,
b: 2,
})

export const output = {
a: 1,
b: 2,
}

export const create = true
9 changes: 9 additions & 0 deletions test/validation/tuple/valid-frozen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { tuple, string, number } from '../../../src'

export const Struct = tuple([string(), number()])

export const data = Object.freeze(['A', 1])

export const output = ['A', 1]

export const create = true
18 changes: 18 additions & 0 deletions test/validation/type/valid-frozen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { type, string, number } from '../../../src'

export const Struct = type({
name: string(),
age: number(),
})

export const data = Object.freeze({
name: 'john',
age: 42,
})

export const output = {
name: 'john',
age: 42,
}

export const create = true

0 comments on commit 23787ae

Please sign in to comment.