Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional support to type. #668

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"import-path-rewrite": "github:gcanti/import-path-rewrite",
"jest": "25.2.7",
"mocha": "7.1.1",
"prettier": "2.0.2",
"prettier": "^2.7.1",
"rimraf": "3.0.2",
"ts-jest": "25.3.1",
"ts-node": "8.8.2",
Expand Down
74 changes: 68 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,12 @@ export interface AnyProps {

function getNameFromProps(props: Props): string {
return Object.keys(props)
.map((k) => `${k}: ${props[k].name}`)
.map((k) => {
if (isOptional(props[k])) {
return `${k}?: ${props[k].name}`
}
return `${k}: ${props[k].name}`
})
.join(', ')
}

Expand Down Expand Up @@ -666,6 +671,10 @@ function isRecursiveC(codec: Any): codec is RecursiveType<Any> {
return (codec as any)._tag === 'RecursiveType'
}

function isOptional(codec: Any): codec is OptionalType {
return (codec as any)._tag === 'OptionalType'
}

const lazyCodecs: Array<Any> = []

/**
Expand Down Expand Up @@ -1320,11 +1329,29 @@ export class InterfaceType<P, A = any, O = A, I = unknown> extends Type<A, O, I>
}
}

export type TypeOfWithOptionalProps<P extends AnyProps> = (
{
[K in keyof P]?: TypeOf<P[K]>
} &
{
[K in keyof P as P[K] extends OptionalType ? never : K]-?: TypeOf<P[K]>
}
)

export type OutputOfWithOptionalProps<P extends AnyProps> = (
{
[K in keyof P]?: OutputOf<P[K]>
} &
{
[K in keyof P as P[K] extends OptionalType<any> ? never : K]-?: OutputOf<P[K]>
}
)

/**
* @since 1.5.3
*/
export interface TypeC<P extends Props>
extends InterfaceType<P, { [K in keyof P]: TypeOf<P[K]> }, { [K in keyof P]: OutputOf<P[K]> }, unknown> {}
extends InterfaceType<P, TypeOfWithOptionalProps<P>, OutputOfWithOptionalProps<P>, unknown> {}

/**
* @category combinators
Expand All @@ -1341,7 +1368,9 @@ export function type<P extends Props>(props: P, name: string = getInterfaceTypeN
for (let i = 0; i < len; i++) {
const k = keys[i]
const uk = u[k]
if ((uk === undefined && !hasOwnProperty.call(u, k)) || !types[i].is(uk)) {
if (uk === undefined && !hasOwnProperty.call(u, k)) {
return isOptional(props[k])
} else if (!types[i].is(uk)) {
return false
}
}
Expand All @@ -1366,7 +1395,7 @@ export function type<P extends Props>(props: P, name: string = getInterfaceTypeN
pushAll(errors, result.left)
} else {
const vak = result.right
if (vak !== ak || (vak === undefined && !hasOwnProperty.call(a, k))) {
if (vak !== ak || (vak === undefined && !hasOwnProperty.call(a, k) && !isOptional(type))) {
/* istanbul ignore next */
if (a === o) {
a = { ...o }
Expand All @@ -1384,8 +1413,9 @@ export function type<P extends Props>(props: P, name: string = getInterfaceTypeN
for (let i = 0; i < len; i++) {
const k = keys[i]
const encode = types[i].encode
if (encode !== identity) {
s[k] = encode(a[k])
const av = a[k]
if (encode !== identity && (av !== undefined || !isOptional(types[i]))) {
s[k] = encode(av)
}
}
return s as any
Expand All @@ -1394,6 +1424,38 @@ export function type<P extends Props>(props: P, name: string = getInterfaceTypeN
)
}

export class OptionalType<A = any, O = A, I = unknown> extends Type<A, O, I> {
constructor(name: string,
is: OptionalType<A, O, I>['is'],
validate: OptionalType<A, O, I>['validate'],
encode: OptionalType<A, O, I>['encode'],
codec: Type<A, O, I>) {
super(name, is, validate, encode)
this._type = codec
}

readonly _type: Type<A, O, I>
readonly _tag: 'OptionalType' = 'OptionalType'
}

export function optional<A, O = A, I = unknown>(
codec: Type<A, O, I>,
name?: string
): OptionalType<A, O, I> {
return new OptionalType<A, O, I>(
name || codec.name,
codec.is,
(u, c) => {
if (u === undefined) {
return success(undefined as A)
}
return codec.validate(u, c)
},
codec.encode,
codec
)
}

/**
* @since 1.0.0
*/
Expand Down