import { z } from "zod";
export enum SUBTYPE {
ABORT = "abort",
START = "start",
UPLOAD = "upload",
LOADING = "loading",
}
export const TYPE = "print";
const PrintBase = z.object({
type: z.literal(TYPE),
subtype: z.nativeEnum(SUBTYPE),
});
type PrintBase = z.infer<typeof PrintBase>;
// start
export const PrintStart = PrintBase.merge(
z.object({
subtype: z.literal(SUBTYPE.START),
attributes: z.object({
tabId: z.number(),
}),
})
);
export type PrintStart = z.infer<typeof PrintStart>;
// upload
export const PrintUpload = PrintBase.merge(
z.object({
subtype: z.literal(SUBTYPE.UPLOAD),
attributes: z.object({
file: z.string(),
tabId: z.number(),
url: z.string().url(),
uniqueFileId: z.string(),
}),
})
);
export type PrintUpload = z.infer<typeof PrintUpload>;
// abort
export const PrintAbort = PrintBase.merge(
z.object({
subtype: z.literal(SUBTYPE.ABORT),
})
);
export type PrintAbort = z.infer<typeof PrintAbort>;
// loading
export const PrintLoading = PrintBase.merge(
z.object({
subtype: z.literal(SUBTYPE.LOADING),
})
);
export type PrintLoading = z.infer<typeof PrintLoading>;
// Print
export const Print = z.discriminatedUnion("subtype", [
PrintStart,
PrintUpload,
PrintLoading,
PrintAbort,
]);
export type Print = z.infer<typeof Print>;
////////TESTING////////////
// #region test data
const printStart = {
type: TYPE,
subtype: SUBTYPE.START,
attributes: {
tabId: 123,
},
} as const;
const printUpload: PrintUpload = {
type: TYPE,
subtype: SUBTYPE.UPLOAD,
attributes: {
file: "file",
tabId: 123,
url: "http://awefa.acom",
uniqueFileId: "awefawe",
},
};
const printLoading: PrintLoading = {
type: TYPE,
subtype: SUBTYPE.LOADING,
};
const printAbort: PrintAbort = {
type: TYPE,
subtype: SUBTYPE.ABORT,
};
// #endregion
function sendPrint<Sub extends SUBTYPE, Action extends Print>(
subtype: Sub,
obj: Action extends { subtype: Sub } ? Action : never
) {}
sendPrint(SUBTYPE.UPLOAD, printUpload);
Print.parse(printUpload);
sendPrint(SUBTYPE.START, printStart);
Print.parse(printStart);
sendPrint(SUBTYPE.LOADING, printLoading);
Print.parse(printLoading);
sendPrint(SUBTYPE.ABORT, printAbort);
Print.parse(printAbort);
标签:Typescript,Zod,subtype,actions,SUBTYPE,export,Print,const,type From: https://www.cnblogs.com/Answer1215/p/16881831.html