Skip to content

Optional non nullable #242

@DrTtnk

Description

@DrTtnk

I have noticed that the t.optional is equivalent to T|undefined|null which may be a quite different behaviour from T|undefined and T, in particular with the new typescript 4.4 --exactOptionalPropertyTypes

Would be possible to add to more optionals to the library? In the specific:

optionalNonNull for undefined properties, compliant with typescript without --exactOptionalPropertyTypes

// Type definition
export declare const optionalNonNull: <RT extends t.Mixed>(rt: RT, name?: string | undefined) => t.UnionC<[RT, t.UndefinedC]> & Optional;

// Implementation
export const optionalNonNull = <RT extends t.Mixed>(rt: RT, name?: string) => {
    const unionType = union([rt, undefinedType], name || rt.name + '?');
    return Object.assign(unionType, { optional: true } as Optional);
};

optionalExact for exact properties, compliant with typescript with --exactOptionalPropertyTypes

// Type definition
export declare const optionalExact: <RT extends t.Mixed>(rt: RT) => RT & Optional;

// Implementation
export const optionalExact = <RT extends t.Mixed>(rt: RT) => {
    return Object.assign(rt, { optional: true } as Optional);
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions