rjhilgefort
2/28/2020 - 5:50 PM

`io-ts` Custom Types

export const NonEmptyStrT = new t.Type<string, string, unknown>(
  'NonEmptyStrT',
  (input): input is string => typeof input === 'string',
  (input, context) =>
    typeof input === 'string' &&
    pipeVal(input, trim, allPass([isString, isNotEmpty]))
      ? right(input)
      : t.failure(input, context, 'string cannot be empty'),
  t.identity,
)
export const ContT = (items: Array<string>) =>
  new t.Type<string, string, unknown>(
    'ContT',
    (u): u is string => typeof u === 'string',
    (u, c) =>
      typeof u === 'string' && allPass([contained(items)])(u)
        ? right(u as string)
        : t.failure(u, c, `${u} not in list [${join(',', items)}]`),
    t.identity,
  )
export const NEmptyArrT = <C extends t.Mixed>(codec: C): t.ArrayC<C> =>
  new t.ArrayType<C>(
    'NEmptyArrT',
    (u): u is Array<t.TypeOf<C>> => t.UnknownArray.is(u) && u.every(codec.is),
    (u, c) =>
      isNotEmpty(u) ? right(u) : t.failure(u, c, 'Array cannot be empty'),
    codec.encode === t.identity ? t.identity : a => a.map(codec.encode),
    codec,
  )