Improved contract hook typings #78
Replies: 3 comments 8 replies
-
Awesome! Will take a deeper look soon. ethers.js v6 should be coming out soon with better TypeScript support for contacts too. |
Beta Was this translation helpful? Give feedback.
-
This looks great! If there's any other typings that can be improved I'm happy to help |
Beta Was this translation helpful? Give feedback.
-
@tmm @ericzakariasson got to work on this today. sorry it took me a bit. basically did the same thing in the snippets above, with one change that I'd like your thoughts on. also, tried to push a branch to start a discussion on a PR but didn't have the permissions. Not sure what the right process is there. So figured I'd ask here first. In the initially proposed typings, users wouldn't be able to use the When no generic is given, we infer read and write method names from the base export class BaseContract {
...
readonly functions: { [ name: string ]: ContractFunction };
...
}
type ContractFunction<T = any> = (...args: Array<any>) => Promise<T>; Because the WriteMethodNames<ethers.Contract> // string
ReadMethodNames<ethers.Contract> // number because keyof { [name: string] ContractFunction } // string | number Didn't think that was a great ux for users who didn't have contract types available to provide generics. The fix changes the type IfNeverThen<T, Then> = [T] extends [never] ? Then : T
export type ReadMethodNames<
Contract extends ethers.Contract,
Methods extends Contract['functions'] = Contract['functions'],
> = IfNeverThen<
{
[M in keyof Methods]: Methods[M] extends GenericWrite ? never : M
}[keyof Methods],
keyof Methods
> Sorry, that was a lot. All in all, it works, but adds a bit more complexity to some typings that are already somewhat opaque. Maybe it's better to not try to differentiate between read and write methods. It wouldn't be as fancy of a ux, but it would simplify the typings. |
Beta Was this translation helpful? Give feedback.
-
I was thinking it would be great to get accurate types on contract method names, args, and return values. I gave it a shot on the
useContractRead
hook and liked the result, so figured I'd start a discussion. Here's the behavior for an IERC20 contract:Usage:
typed
data
:typed function names for read methods only. So here we're trying to use
approve
, which is an IERC20 method, but not allowed for this hook:typed args:
Could also be nice to require
args
via the Config param if the read func does in fact take arguments, though I didn't try that out.Here's one way to get these typings. Feedback appreciated.
The
Writes
type is unused but I left it in there for symmetry. And to show we could do something similar for theuseContractWrite
hook.Beta Was this translation helpful? Give feedback.
All reactions