gcanti / io-ts

Runtime type system for IO decoding/encoding
https://gcanti.github.io/io-ts/
MIT License
6.68k stars 331 forks source link

[Question] How to implement a codec that works with any array or string codecs? #673

Open arthurgubaidullin opened 1 year ago

arthurgubaidullin commented 1 year ago

I want to be able to chain codecs in a pipeline.

That doesn't work.

import {pipe} from 'fp-ts/function';
import * as t from 'io-ts';
import {
  NonEmptyArrayC,
  readonlyNonEmptyArray,
  ReadonlyNonEmptyArrayC,
} from 'io-ts-types';

type LenghtUpTo1000Brand = {
  readonly LenghtUpTo1000: unique symbol;
};

const LengthUpTo1000 = <
  C extends
    | t.ArrayType<t.Mixed>
    | t.ReadonlyArrayType<t.Mixed>
    | NonEmptyArrayC<t.Mixed>
    | ReadonlyNonEmptyArrayC<t.Mixed>
>(
  codec: C
) =>
  t.brand(
    codec,
    (a): a is t.Branded<t.TypeOf<C>, LenghtUpTo1000Brand> => a.length <= 1000,
    'LenghtUpTo1000'
  );

export const DataCodec = pipe(t.array(t.string), LengthUpTo1000);

export const DataCodec2 = pipe(t.readonlyArray(t.string), LengthUpTo1000);

export const DataCodec3 = pipe(readonlyNonEmptyArray(t.string), LengthUpTo1000);  // <- error

Any ideas?