Skip to content

Commit

Permalink
fix(types): Optional JSON params where undefined is not valid (#134)
Browse files Browse the repository at this point in the history
* fix(types): Optional JSON params where undefined is not valid
* Reduce type duplication by excluding `undefined`

---------

Co-authored-by: Maarten Zuidhoorn <[email protected]>
  • Loading branch information
legobeat and Mrtenz authored Aug 31, 2023
1 parent 58b1611 commit e8cad2f
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
nullable,
number,
object,
omit,
optional,
record,
string,
Expand Down Expand Up @@ -178,36 +177,35 @@ export type JsonRpcError = OptionalField<
>;

export const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =
optional(union([record(string(), JsonStruct), array(JsonStruct)])) as any;
union([record(string(), JsonStruct), array(JsonStruct)]);

export type JsonRpcParams = Json[] | Record<string, Json>;

export const JsonRpcRequestStruct = object({
id: JsonRpcIdStruct,
jsonrpc: JsonRpcVersionStruct,
method: string(),
params: JsonRpcParamsStruct,
params: optional(JsonRpcParamsStruct),
});

export type InferWithParams<
Type extends Struct<any>,
Params extends JsonRpcParams,
> = Omit<Infer<Type>, 'params'> &
(keyof Params extends undefined
? {
params?: Params;
}
: {
params: Params;
});
> = Omit<Infer<Type>, 'params'> & {
params?: Exclude<Params, undefined>;
};

/**
* A JSON-RPC request object.
*/
export type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =
InferWithParams<typeof JsonRpcRequestStruct, Params>;

export const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);
export const JsonRpcNotificationStruct = object({
jsonrpc: JsonRpcVersionStruct,
method: string(),
params: optional(JsonRpcParamsStruct),
});

/**
* A JSON-RPC notification object.
Expand Down

0 comments on commit e8cad2f

Please sign in to comment.