Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,25 @@ export const JsonRpcErrorStruct = object({
stack: optional(string()),
});

/**
* Mark a certain key of a type as optional.
*/
export type OptionalField<
Type extends Record<string, unknown>,
Key extends keyof Type
> = Omit<Type, Key> & Partial<Pick<Type, Key>>;

/**
* A JSON-RPC error object.
*
* Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that
* the `data` field is not optional. To make it optional, we use the
* `OptionalField` helper, to explicitly make it optional.
*/
export type JsonRpcError = Infer<typeof JsonRpcErrorStruct>;
export type JsonRpcError = OptionalField<
Infer<typeof JsonRpcErrorStruct>,
'data'
>;

export const JsonRpcParamsStruct = optional(union([object(), array()]));

Expand Down Expand Up @@ -224,7 +239,7 @@ export type JsonRpcSuccess<Result extends Json> = Omit<
export const JsonRpcFailureStruct = object({
id: JsonRpcIdStruct,
jsonrpc: JsonRpcVersionStruct,
error: JsonRpcErrorStruct,
error: JsonRpcErrorStruct as Struct<JsonRpcError>,
});

/**
Expand Down