shogowada / json-rpc-2.0

Let your client and server talk over function calls under JSON-RPC 2.0 spec. Strongly typed. No external dependencies.
https://www.npmjs.com/package/json-rpc-2.0
MIT License
193 stars 25 forks source link

JSONRPCParams typing issue #41

Closed segevfiner closed 1 year ago

segevfiner commented 2 years ago

https://github.com/shogowada/json-rpc-2.0/blob/7bc786c03b47b1e0a93e1d8b9df2c6a2d42a4094/src/models.ts#L5

Should probably be:

export type JSONRPCParams = any | any[];

Or just:

export type JSONRPCParams = any;

Or you will get errors from TypeScript while trying to destructure params or to type it as object is akin to {}, an object with no known props.

shogowada commented 2 years ago

you will get errors from TypeScript while trying to destructure params

Do you mean the code like this gives you an error?

serverAndClient1.addMethod("echo", ({ message }) => message);

If so, it is intentional to enforce type annotation:

interface EchoParams {
  message: string
}

serverAndClient1.addMethod("echo", ({ message }: EchoParams) => message);
segevfiner commented 2 years ago

you will get errors from TypeScript while trying to destructure params

Do you mean the code like this gives you an error?

serverAndClient1.addMethod("echo", ({ message }) => message);

If so, it is intentional to enforce type annotation:

interface EchoParams {
  message: string
}

serverAndClient1.addMethod("echo", ({ message }: EchoParams) => message);

I was getting an error trying to annotate the parameter or destructure it, so I was actually getting an error on the second example, had to use an as cast inside the method code and destructure there.

shogowada commented 2 years ago

Can you please give me minimal reproducible example?

segevfiner commented 2 years ago

Try this: https://github.com/segevfiner/json-rpc-2.0-types-issue, just a pnpm build should show the issue.

shogowada commented 1 year ago

Is this the error you are getting?

src/index.ts:5:27 - error TS2345: Argument of type '({ name }: { name?: string | undefined; }) => void' is not assignable to parameter of type 'SimpleJSONRPCMethod<void>'.
  Types of parameters '__0' and 'params' are incompatible.
    Type 'Partial<JSONRPCParams> | undefined' is not assignable to type '{ name?: string | undefined; }'.
      Type 'undefined' is not assignable to type '{ name?: string | undefined; }'.

It's strange how the same code works in this repo if I copy and paste it. I'll take a look.

shogowada commented 1 year ago

Adding "strictFunctionTypes": true to tsconfig.json surfaces this error. In your example, "extends": "@tsconfig/node16/tsconfig.json" inherits this setting.

Let me think of something so that it works with strict mode! Thank you for reporting.