zod
zod copied to clipboard
Support TS 4.7 instantiation expressions
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";
}
}
Related: https://github.com/colinhacks/zod/issues/153
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.
bump
Since typescript's official version is now, as of this writing, 4.7.4 would it be possible to prioritise this feature now?
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.
Hey guys, why is this issue closed?
@dilame as you can see, it is closed because @stale decided to close it and nobody cared enough to bump