zod icon indicating copy to clipboard operation
zod copied to clipboard

Support TS 4.7 instantiation expressions

Open cyberia-ng opened this issue 2 years ago • 4 comments

TS 4.7.0 (currently in beta) will bring in "Instantiation Expressions" (see https://github.com/microsoft/TypeScript/pull/47607).

Essentially this means that you can write things like:

function foo<T>(val: T) {}
type Foo<T> = typeof foo<T>
// type Foo<T> = (val: T) => void

The application for Zod schemas is as detailed here (https://github.com/microsoft/TypeScript/issues/40542), in particular that we can now write such things as:

// the dateSchema param could be a schema for an ISO 8601 string or a Date object, or even some custom date-like type
const fooSchema = <T>(dateSchema: z.ZodSchema<T>) => z.object({
  name: z.string(),
  date: dateSchema
})
type Foo<T> = z.infer<ReturnType<(typeof fooSchema)<T>>>
// expected result: type Foo<T> = { name: string, date: T }

Unfortunately this does not "Just Work" by upgrading to TS 4.7.0-beta:

import { z } from "zod";

function genericFooSchema<T>(inner: z.Schema<T>) {
  return z.object({
    type: z.literal("foo"),
    inner,
  });
}

type Foo<T> = z.infer<ReturnType<typeof genericFooSchema<T>>>;

function useAFoo<T>(foo: Foo<T>): string {
  switch (foo.type) {
    // Hovering over foo.type gives:
    // ```
    // (property) type: z.objectUtil.addQuestionMarks<{
    //     type: "foo";
    //     inner: T;
    // }>["type"]
    // ```

    case "foo":
      return "TS should infer that this switch is exhaustive";
  }
}

cyberia-ng avatar Apr 28 '22 17:04 cyberia-ng

Related: https://github.com/colinhacks/zod/issues/153

cyberia-ng avatar May 16 '22 23:05 cyberia-ng

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 15 '22 23:07 stale[bot]

bump

aganoza avatar Jul 21 '22 02:07 aganoza

Since typescript's official version is now, as of this writing, 4.7.4 would it be possible to prioritise this feature now?

max-abclabs avatar Aug 02 '22 13:08 max-abclabs

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Oct 01 '22 22:10 stale[bot]

Hey guys, why is this issue closed?

dilame avatar Nov 29 '22 19:11 dilame

@dilame as you can see, it is closed because @stale decided to close it and nobody cared enough to bump

FlorianWendelborn avatar Nov 30 '22 17:11 FlorianWendelborn