Skip to content

Commit be4bc95

Browse files
authored
Allow frozen objects/arrays to be coerced (#1151)
* Add frozen objects/arrays tests * Update record coercer * Update tuple coercer * Update `record()` struct to only coerce non-array objects
1 parent 5d18222 commit be4bc95

File tree

6 files changed

+75
-0
lines changed

6 files changed

+75
-0
lines changed

src/structs/types.ts

+6
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,9 @@ export function record<K extends string, V>(
386386
`Expected an object, but received: ${print(value)}`
387387
)
388388
},
389+
coercer(value) {
390+
return isNonArrayObject(value) ? { ...value } : value
391+
},
389392
})
390393
}
391394

@@ -473,6 +476,9 @@ export function tuple<A extends AnyStruct, B extends AnyStruct[]>(
473476
`Expected an array, but received: ${print(value)}`
474477
)
475478
},
479+
coercer(value) {
480+
return Array.isArray(value) ? value.slice() : value
481+
},
476482
})
477483
}
478484

test/validation/array/valid-frozen.ts

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { array, number } from '../../../src'
2+
3+
export const Struct = array(number())
4+
5+
export const data = Object.freeze([1, 2, 3])
6+
7+
export const output = [1, 2, 3]
8+
9+
export const create = true
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { object, string, number } from '../../../src'
2+
3+
export const Struct = object({
4+
name: string(),
5+
age: number(),
6+
})
7+
8+
export const data = Object.freeze({
9+
name: 'john',
10+
age: 42,
11+
})
12+
13+
export const output = {
14+
name: 'john',
15+
age: 42,
16+
}
17+
18+
export const create = true
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { record, string, number } from '../../../src'
2+
3+
export const Struct = record(string(), number())
4+
5+
export const data = Object.freeze({
6+
a: 1,
7+
b: 2,
8+
})
9+
10+
export const output = {
11+
a: 1,
12+
b: 2,
13+
}
14+
15+
export const create = true

test/validation/tuple/valid-frozen.ts

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { tuple, string, number } from '../../../src'
2+
3+
export const Struct = tuple([string(), number()])
4+
5+
export const data = Object.freeze(['A', 1])
6+
7+
export const output = ['A', 1]
8+
9+
export const create = true

test/validation/type/valid-frozen.ts

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { type, string, number } from '../../../src'
2+
3+
export const Struct = type({
4+
name: string(),
5+
age: number(),
6+
})
7+
8+
export const data = Object.freeze({
9+
name: 'john',
10+
age: 42,
11+
})
12+
13+
export const output = {
14+
name: 'john',
15+
age: 42,
16+
}
17+
18+
export const create = true

0 commit comments

Comments
 (0)