Skip to content

TypeScript right adapt constructor #57812

Open
@little-alei

Description

@little-alei

🔍 Search Terms

I have implemented a function JavaAdapter to inherit classes and return instantiated objects. Now I'm creating a declaration for it.

type ProxyMethods<T extends object> = { [K in keyof T]?: T[K] } | {};

declare function JavaAdapter<T, K extends ProxyMethods<T>, Args>(
  className: new (...args: Args) => T,
  override: K,
  ...args: Args
): K & T;

In most cases, it works fine. However, when the inherited object has multiple constructor functions with different parameter counts, it cannot accurately match, for example:

JavaAdapter(
  android.widget.Button,
  {
    setOnClickListener(view) {
      console.log(view);
    },
  },
  activity,
  // new android.util.AttributeSet()
);

This usage is correct and matches one of the constructor functions, but TypeScript prompts "Expected 4 arguments, but got 3." It works only when I add new android.util.AttributeSet(). The partial declaration of android.widget.Button is as follows:

declare module android {
  export module widget {
    class Button {
      public setOnClickListener(view: this): void;
      public constructor(context: android.content.Context);
      public constructor(context: android.content.Context, attribute: android.util.AttributeSet);
    }
  }
}

Besides changing to constructor(context: android.content.Context, attribute?: android.util.AttributeSet);, can TypeScript better adapt?

✅ Viability Checklist

⭐ Suggestion

TypeScript matches correctly based on parameters

📃 Motivating Example

Enhance the user experience of typescript

💻 Use Cases

  1. What do you want to use this for?
  2. What shortcomings exist with current approaches?
  3. What workarounds are you using in the meantime?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs More InfoThe issue still hasn't been fully clarified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions