Skip to content

Instantly share code, notes, and snippets.

@davidonlaptop
Last active July 30, 2023 20:26
Show Gist options
  • Save davidonlaptop/43f57e88b73f9b5d2d942dd0c6c78385 to your computer and use it in GitHub Desktop.
Save davidonlaptop/43f57e88b73f9b5d2d942dd0c6c78385 to your computer and use it in GitHub Desktop.
typescript-hacks

Typescript Hacks

Tuples

Variadic Tuple using Spread operator

Plain typescript

type VariadicTuple = [string, ...number[]];

var vt: VariadicTuple;

// Valid
vt = ["str"];
vt = ["str", 1];
vt = ["str", 1, 2, 3];

// Invalid
vt = ["str", 1, 2, 3, "bad"];

Plain typescript with minimum one item

type VariadicTupleWithMinimum = [string, number, ...number[]];

var vtm: VariadicTupleWithMinimum;

// Valid
vtm = ["str", 1];
vtm = ["str", 1, 2, 3];

// Invalid
vtm = ["str"];
vtm = ["str", 1, 2, 3, "bad"];

Using Zod

import { z } from "zod";

const ZodVariadicTuple = z.tuple([z.string()]).rest(z.number());
type ZodVariadicTuple = z.infer<typeof ZodVariadicTuple>;

let zvt: ZodVariadicTuple;

// Valid
zvt = ["str"];
zvt = ["str", 1];
zvt = ["str", 1, 2, 3];

// Invalid
zvt = ["str", 1, 2, 3, "bad"];

Using Zod with minimum 1 item

import { z } from "zod";

const ZodVariadicTupleMin = z.tuple([z.string(), z.number()]).rest(z.number());
type ZodVariadicTupleMin = z.infer<typeof ZodVariadicTupleMin>;

let zvtm: ZodVariadicTupleMin;

// Valid
zvtm = ["str", 1];
zvtm = ["str", 1, 2, 3];

// Invalid
zvtm = ["str"];
zvtm = ["str", 1, 2, 3, "bad"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment