-
Notifications
You must be signed in to change notification settings - Fork 5
/
partial.ts
29 lines (24 loc) · 916 Bytes
/
partial.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { optional } from './optional'
import { internalRecord } from './record'
import { InternalRuntype, Runtype, RuntypeUsageError } from './runtype'
/**
* Build a new record runtype that marks all keys as optional.
*
* This is the runtype counterpart to `Partial<T>`.
*/
export function partial<T>(original: Runtype<T>): Runtype<Partial<T>> {
const fields = (original as InternalRuntype<any>).meta?.fields
const isNonStrict = (original as InternalRuntype<any>).meta?.isNonStrict
if (!fields) {
throw new RuntypeUsageError(`expected a record runtype`)
}
const newRecordFields: any = {}
for (const k in fields) {
if (Object.prototype.hasOwnProperty.call(fields, k)) {
// TODO: detect whether field is already optional and do not apply
// optional a second time
newRecordFields[k] = optional(fields[k])
}
}
return internalRecord(newRecordFields, isNonStrict)
}