Converting `undefined` and `null` to a missing value in TypeScript using Effect's schema transfor...

Does this seem like a sane way to convert undefined/null/<missing value> to just <missing value>?

const UndefinedFromNull = <T extends S.Schema.Any>(schema: T) =>
  S.transform(S.NullishOr(schema), S.NullOr(schema), {
    strict: true,
    encode: v => v || null,
    decode: v => v || null
  });

export const UnDeleteableRootField = <T extends S.Schema.Any>(schema: T) =>
  S.optionalWith(UndefinedFromNull(schema), { nullable: true, exact: true });


/* test for extra clarity */

describe('UnDeleteableRootField', () => {
  const schema = S.Struct({ foo: UnDeleteableRootField(S.String) });
  const decodeSync = S.decodeSync(schema);

  it('should convert undefined/null/missing to missing', () => {
    const whenMissing = decodeSync({});
    const whenUndefined = decodeSync({ foo: undefined });
    const whenNull = decodeSync({ foo: null });

    expect(whenMissing).not.toHaveProperty('foo');
    expect(whenUndefined).not.toHaveProperty('foo');
    expect(whenNull).not.toHaveProperty('foo');
  });
});


Context:

* I have some fields that should not be deletable in update operations
* The call-sites often have to deal with the values possibly being undefined/null regardless of whether or not the intention is to delete a given field
* In the database I'm working with:
* null can mean "remove this field"
* If the field is missing in the update payload, it will leave the field alone in the database
* So...I want a schema that will remove the field from the payload if it's undefined/null to prevent anyone from unintentionally deleting the field

It was bugging me that I could convert null to <missing value> but couldn't do the same for undefined
Was this page helpful?