Home > OS >  Typescript polymorphism: inference of return type for parent method which uses child property/method
Typescript polymorphism: inference of return type for parent method which uses child property/method

Time:10-27

I'm new to TypeScript and having a hard time with something. I have searched Google & SO comprehensively. The following code works with no errors, the problem is TS and the IDE are not aware of the correct return types, which defeats the purpose of the architecture.

class Data {
 schema: z.Schema<any>

  parse(): this["parse"] {
    return this.schema.parse({});
  }
}

class LoginData extends Data {
 schema = z.object({
    email: z.string(),
    password: z.string()
  })
}
const data = new LoginData().parse();

When adding the parse method directly to the LoginData class, TS is able to infer the return type correctly:

But when using the parent method directly, TS gets confused:

CodePudding user response:

If we do some trickery we can pass the child class to the parent class like this:

import z from "zod";

abstract class Data<T extends { schema: z.Schema<any> }> {
    abstract schema: T["schema"];

    parse(): z.infer<T["schema"]> {
        return this.schema.parse({});
    }
}

class LoginData extends Data<LoginData> {
    schema = z.object({
        email: z.string(),
        password: z.string(),
    });
}

Then in the parent class, we can get the schema with T["schema"] and use it however we'd like. Here, we're using it as the type of schema, and the return type of parse. This works since the type of schema in the parent class is now the same type of schema in the child class.

z.infer is a built-in type from Zod that gives us the parsed type from a schema.

Playground

  • Related