Skip to content

Feature: 'nullToUndefined' decoder type #37

@marcbinz

Description

@marcbinz

Many APIs provide missing data fields with a value of null (see issue #29).

As a consumer of such an API using TypeScript and this very library it is currently not possible to decode such values to undefined.

Personally, I prefer to use undefined instead of null for my TypeScript models and I try to avoid null wherever possible. While this might be just my own preference, I believe it would make sense to add a standard decoder to this library that will automatically transform a given null value to undefined.

Here is snippet that does exactly what I need:
const nullToUndefined = <T>(decoder: Decoder<T>): Decoder<T | undefined> => JTV.union(decoder, JTV.constant(null)).map((val) => val === null ? undefined : val);

I am not sure if this is the best solution to the given problem, but it works.
I am happy to file a PR if that is desired 🙂

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions