Skip to content

Make property decorator fabrics share generics with corresponding methodsΒ #58649

Closed
@finom

Description

@finom

πŸ” Search Terms

decorator generic
decorator set type

βœ… Viability Checklist

⭐ Suggestion

There are multiple requests to be able to modify class or its methods type

#4881
#49229

But I haven't found a much simpler request: be able to share property decorator fabric generic with its method.

πŸ“ƒ Motivating Example

There is the decorator fabric example, nothing fancy:

function paramDecoratorFabric<T>(arg: T) {
  return function (target: any, propertyKey: string) {
    console.log('Parameter Decorator called on: ', arg);
  }
}

And there is what I would be happy to be able to achieve:

class ParameterDecoratorExample {
  method<T>(@paramDecoratorFabric<T>('Hello') param: T) {
    return param;
  }
}

Unfortunately, I get the following error:

image

Which says that the T of @paramDecoratorFabric is kind of a different thing that doesn't belong to the "place" where it was used.

πŸ’» Use Cases

I'm actively working on my RPC-ish library and one of the biggest downsides comparing to other RPC libraries is inability to automatically recognise Zod types provided at the controller. This requires to add the type to the controller method manually but also to create extra variables.

export default class UserController {
    @put()
    @vovkZod(UpdateUserModel, UpdateUserQueryModel)
    static updateUser(
        req: VovkRequest<z.infer<typeof UpdateUserModel>, z.infer<typeof UpdateUserQueryModel>>
    ) {
        // ...
    }
}

I understand that adding ability to modify method/class type by a decorator is quite challenging. But I hope that changing the "scope" of generics isn't that big deal. With the feature I'm requesting I would be able to achieve the goal without defining extra variables:

export default class UserController {
  @put()
  static updateUser<B, Q>(
    @vovkZod<B, Q>(z.object({ /*...*/ }), z.object({ /*...*/ })) req: VovkRequest<B, Q>
  ) {
      // ...
  }
}

The method and the parameter already share B and Q, and since @vovkZod is used "inside" of this definition, it makes sense for it to be able to also use B and Q.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions