Skip to content

Question: How to make a tuple with more than 5 types? #431

Open
@Picoseconds

Description

@Picoseconds

If I use t.tuple, it starts to error once I put 6 types. This is my code:
t.tuple([t.number, t.number, t.number, t.number, t.number, t.number, t.any, t.number])

Activity

ForbesLindesay

ForbesLindesay commented on Apr 9, 2020

@ForbesLindesay

I've submitted a PR that resolves this, but only for TypeScript 3.8+. If you're using TypeScript 3.8, you can workaround this for now via:

type TupleFn = <TCodecs extends readonly t.Mixed[]>(
  codecs: TCodecs,
  name?: string,
) => t.TupleType<
  {
    -readonly [K in keyof TCodecs]: TCodecs[K];
  },
  {
    [K in keyof TCodecs]: TCodecs[K] extends t.Mixed
      ? t.TypeOf<TCodecs[K]>
      : unknown;
  },
  {
    [K in keyof TCodecs]: TCodecs[K] extends t.Mixed
      ? t.OutputOf<TCodecs[K]>
      : unknown;
  }
>;
const tuple: TupleFn = t.tuple as any;

and then use tuple in place of t.tuple.

ForbesLindesay

ForbesLindesay commented on Apr 9, 2020

@ForbesLindesay

Forgot to mention, you will also need to mark the input as const e.g.

t.tuple([
  t.number, t.number, t.number, t.number, t.number, t.number, t.any, t.number,
] as const)
ForbesLindesay

ForbesLindesay commented on Apr 10, 2020

@ForbesLindesay

You can actually make it work without the as const:

type TupleFn = <TCodecs extends readonly [t.Mixed, ...t.Mixed[]]>(
  codecs: TCodecs,
  name?: string,
) => t.TupleType<
  {
    -readonly [K in keyof TCodecs]: TCodecs[K];
  },
  {
    [K in keyof TCodecs]: TCodecs[K] extends t.Mixed
      ? t.TypeOf<TCodecs[K]>
      : unknown;
  },
  {
    [K in keyof TCodecs]: TCodecs[K] extends t.Mixed
      ? t.OutputOf<TCodecs[K]>
      : unknown;
  }
>;
const tuple: TupleFn = t.tuple as any;

This forces TypeScript to infer TCodecs as a tuple, rather than an array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @ForbesLindesay@Picoseconds

      Issue actions

        Question: How to make a tuple with more than 5 types? · Issue #431 · gcanti/io-ts