Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Picoseconds opened this issue Mar 30, 2020 · 3 comments · May be fixed by #441
Open

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

Picoseconds opened this issue Mar 30, 2020 · 3 comments · May be fixed by #441

Comments

@Picoseconds
Copy link

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])

@ForbesLindesay
Copy link

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
Copy link

ForbesLindesay commented Apr 9, 2020

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
Copy link

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
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants