Skip to content

nullable()

ts
function nullable<T>(parser): Parser<null | T>

Represents a value that can be null. Shorthand for oneOf(parseNull, parser).

Example

ts
const parseNullableString = nullable(parseString)
parseNullableString(null) // => ParseSuccess<string | null>
parseNullableString('abc') // => ParseSuccess<string | null>

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
parserParser<T>a parser function.

Returns

Parser<null | T>


optional()

ts
function optional<T>(parser): OptionalParser<T>

Represent an optional property in an object. It is supposed to be used in combination with object. Note that in TypeScript, optional properties may be assigned undefined or omitted entirely from the object. This function is special because it is used internally by object to differentiate between optional properties from required properties that can be undefined. Only use this in objects: it can return the OmitProperty symbol to indicate that the property was omitted from the object.

Example

Wrap properties in optional to make them optional:

ts
type User = {
 id: number
 email?: string
}
const parseUser = object<User>({
  id: parseNumber,
  email: optional(parseString),
})
parseUser({ id: 123 }) // -> ParseSuccess
parseUser({ id: 123, email: undefined }) // -> ParseSuccess
parseUser({ id: 123, email: 'abc@test.com' }) // -> ParseSuccess

If email instead was defined as a union of string and undefined, the first call to parseUser would fail.

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
parserParser<T>A parser to parse the property with.

Returns

OptionalParser<T>

a special parser that represents an optional value. If invoked directly, it behaves the same as oneOf(parseUndefined, parser). If invoked by object, object will treat the property as optional.


optionalNullable()

ts
function optionalNullable<T>(parser): OptionalParser<null | T>

Represents an optional property that can also be null. Shorthand for optional(oneOf(parseNull, parser)).

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
parserParser<T>a parser function.

Returns

OptionalParser<null | T>


undefineable()

ts
function undefineable<T>(parser): Parser<undefined | T>

Represents a value that can be undefined. Shorthand for oneOf(parseUndefined, parser).

Example

ts
const parseUndefineableString = undefineable(parseString)
parseUndefineableString(undefined) // => ParseSuccess<string | undefined>
parseUndefineableString('abc') // => ParseSuccess<string | undefined>

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
parserParser<T>

Returns

Parser<undefined | T>