Effect CommunityEC
Effect Community16mo ago
4 replies
Thr1ve

Handling Missing, Null, Undefined, and Empty Strings with Default Values in TypeScript Structs

Is there a cleaner way to do this?

export const DEFAULT_TIMEZONE = 'America/New_York';

const EmptyToDefault = S.transform(S.String, S.String, {
  strict: true,
  decode: str => (str.length === 0 ? DEFAULT_TIMEZONE : str),
  encode: identity
});

export const MyStruct = S.Struct({
  timezone: S.optionalWith(EmptyToDefault, {
    nullable: true,
    default: () => DEFAULT_TIMEZONE
  })
  // ...
});


Basically, I want to turn <missing> | null | undefined | "" into the default value...and this is the only way I've found so far that seems to work.

I'd love to be able to say something like the below (although I doubt it would actually be possible):
// ...
timezone: S.optionalWith(S.String, {
  emptyAsMissing: true,
  nullable: true,
  default: () => DEFAULT_TIMEZONE
})
// ...
Was this page helpful?