Skip to content

Optional Properties #4

@chris-pardy

Description

@chris-pardy

Currently type-shift support "optional" properties which are really just a shorthand syntax for "undefined or X". For instance these two converters are equivalent: t.undefined.or(t.string) t.optional(t.string).

While this works in many cases typescript and other javascript typing tools (eg. flow) have support for denoting the difference between present and undefined vs. missing or undefined. Specifically the following typescript types are not equivalent:

interface Missing {
   // property can be not-present (ie. 'optionalProperty' in m === false),
  // undefined, or string
   optionalProperty?: string;
}

interface Present {
   // property can be undefined or string
   optionalProperty: string | undefined;
}

const m: Missing = {};
const p: Present = { optionalProperty: undefined };

// failure, Missing cannot be assigned to Present
const p2 = m;
// success Present can be assigned to Missing
const m2 = p;

type-shift should be able to support this dichotomy. I'd propose doing this with the optional decorator.

const missingConverter = t.strict<Missing>({ optionalProperty: t.optional(t.string) });
const presentConverter = t.strict<Present>({ optionalProperty: t.string.or(t.undefined) });

In order to support this converters will need a way to signal that a the value that is being passed to them is not present (note that this is different than undefined). Some options include:

  • Create a seperate optional method on converters called: convertOptional which would not take a value.
  • Create a simple "optional" wrapper for all values.
  • Create a "MISSING" value

Of these options both the optional wrapper and the missing value require all type converters and type converter functions to handle these values in some way. Adding a new method allows converters like strict and shape to build special handling for optional conversion. However it makes handling optional values in your own converter much harder. Additionally that optional conversion function needs a way to indicate that the result should be a missing value.

I'd propose the introduction of a simple optional wrapper and the introduction of a required decorator. The required decorator would handle creating errors in the event of being massed a missing value allowing most converters to simply think about present values. This would allow the optional converters to build special functionality around missing values including returning missing values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions