ts icon indicating copy to clipboard operation
ts copied to clipboard

Optional non nullable

Open DrTtnk opened this issue 3 years ago • 0 comments

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);
};

DrTtnk avatar Sep 10 '21 10:09 DrTtnk