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

type guards for classes #352

Closed
insomnimus opened this issue Mar 12, 2025 · 4 comments
Closed

type guards for classes #352

insomnimus opened this issue Mar 12, 2025 · 4 comments

Comments

@insomnimus
Copy link

Is it possible to generate type guards for classes as well?

I'm currently facing a problem where I need to declare what used to be an interface as a class due to @nestjs/swagger requiring classes for the decorators to work.
ts-auto-guard does not seem to generate any type guard for classes. Is this intended behaviour?

@rhys-vdw
Copy link
Owner

@insomnimus you can do: myInstance instanceof SomeClass in JS. You don't need any codegen.

@insomnimus
Copy link
Author

I'm instantiating this class from JSON. I need to define the request body an endpoint expects, and since decorators don't work on interfaces (at least the ones I'm using don't), nestjs/swagger requires me to use classes for the DTO.

If there isn't a technical blocker for this feature, I think it would be nice to have the option to be able to generate guards for classes, as the generated code should be exactly the same.

@rhys-vdw
Copy link
Owner

rhys-vdw commented Mar 18, 2025

Your scenario doesn't make sense to me. A class is based on prototype chain. There is no such thing as instantiating a class from JSON (at least not standard JSON), because JSON can't set __proto__. Therefore the result will always be false unless you want it to lie to you. Objects can only fulfill interfaces/types, not classes, so probably you would need to do something like this:

/** @see {isFoo} ts-auto-guard:type-guard */
interface Foo {
  x: number;
  y: string;
}

class FooClass implements Foo {}

let payload = await getMyPayload()
if (!isFoo(payload)) {
  throw new Error("That isn't foo!");
}

let new fooClass = new Foo();
Object.assign(fooClass, payload);

@rhys-vdw
Copy link
Owner

btw this project is basically dead, maybe you could try asking over at https://typia.io/

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

No branches or pull requests

2 participants