Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zod.function as property of zod.object loses this #2651

Closed
ddurschlag opened this issue Aug 14, 2023 · 0 comments · Fixed by #2652
Closed

zod.function as property of zod.object loses this #2651

ddurschlag opened this issue Aug 14, 2023 · 0 comments · Fixed by #2652

Comments

@ddurschlag
Copy link
Contributor

Quoting myself from discord:

const MyObj = z.object({ foo: z.function() });
class MyObjImpl implements z.infer<typeof MyObj> { private bar: string; constructor(){this.bar = 'baz';} foo() { console.log(this.bar); } };
const inst = MyObj.parse(new MyObjImpl()); //ok
inst.foo(); // kablooey :( "this is undefined"

The problem is that the parsed object's parsed method is an arrow function, and thus has a "this" of the ZodFunction (see:

zod/src/types.ts

Line 3755 in 1ecd624

return OK((...args: any[]) => {
). A similar problem applies to async functions.

I can think of two possible solutions here. First is to make the parsed result a normal function instead of an arrow function, then apply its this to the underlying fn. The second is to use proxies on either the parsed function, the parsed object, or both to get a similar behavior.

I'll have a not-yet-mergeable PR for the former strategy up for this shortly. Would love help getting it over the line.

colinhacks pushed a commit that referenced this issue Aug 15, 2023
* Initial prototype fix

* Add implementation/test for async

* Fix formatting
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant