Saturday, 10 June 2023

How to override interface in a function and maintain the correct return type?

I have a definePlugin function that accepts an object implementing the PluginConfig interface, with a default RequestValidator. I’m trying to override this interface, providing a custom validator while ensuring the returned value has the correct type. However, my current implementation results in the returned vueAuth having the type any. How do I override the interface while maintaining the correct return type? Here’s my current code:

import { z } from 'zod'

// Create de default validator
export const EmailValidator = z.object({
  email: z
    .string({ required_error: 'auth.validation.email' })
    .email({ message: 'auth.validation.email_format' })
})

// The default interface the generic should at least implement
interface PluginConfig {
  validator?: z.ZodType
}

// The default interface with the default validator to use if not overriden
interface DefaultPluginConfig {
  validator?: typeof EmailValidator
}

const definePlugin = <T extends PluginConfig = DefaultPluginConfig>({
  validator = EmailValidator
}: T) => {
  return validator.parse({})
}

const test = definePlugin({})
// Object should look like EmailValidator but is any instead
test.email

// Create a custom validator
const CustomValidator = z.object({
  email: z.string(),
  username: z.string()
})

// Create a custom interface to use as generic
interface CustomConfig {
  validator?: typeof CustomValidator
}

const test2 = definePlugin<CustomConfig>({
  validator: CustomValidator
})
// Object should look like CustomValidator but is any instead
test2.username
test2.username

What changes should I make to ensure that definePlugin has the correct type when providing a custom validator?



from How to override interface in a function and maintain the correct return type?

No comments:

Post a Comment