withDefault()
ts
function withDefault<T, F>(parser, fallbackValue): InfallibleParser<T | F>
Provide a default value to fall back to when parsing fails. Since the default value is static, the parser will always succeed.
See
oneOf for a more flexible alternative.
Type Parameters
Type Parameter |
---|
T |
F |
Parameters
Parameter | Type | Description |
---|---|---|
parser | Parser <T > | |
fallbackValue | F |
Returns
InfallibleParser
<T
| F
>
Examples
Parse a number with a default value:
ts
const parseNum = withDefault(parseNumber, 0)
parseNum(1) // -> ParseSuccess<number>
parseNum(null) // -> ParseSuccess<0>
Parse an array of objects, but replace the objects with a default value if the parsing fails:
ts
const parseContent = array(
withDefault(
object({
tag: equals('text'),
value: parseString,
}),
{
tag: 'unknown',
},
),
)
const res = parseContent([{
tag: 'text',
value: 'hello'
}, {
tag: 'number'
value: 123
}])
where res becomes:
ts
[
{ tag: 'text', value: 'hello'},
{ tag: 'unknown' }
]
Calling withDefault
is almost the same as:
ts
oneOf(parser, () => success(fallbackValue))
The only difference is that the return type of the parser will always be a success.