Skip to content

How to distinguish a method property from a bound callback property? #49847

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

Closed
dko-slapdash opened this issue Jul 10, 2022 · 2 comments
Closed
Labels
Question An issue which isn't directly actionable in code

Comments

@dko-slapdash
Copy link

dko-slapdash commented Jul 10, 2022

Suggestion

I expected ThisParameterType helper to be able to distinguish between methods (unbound function properties) and callbacks (bound functions), but it doesn't want to do it:

class Cls {
  method() {}
  callback = () => {}
}

type aaa = ThisParameterType<Cls["callback"]>;
// Aaa = unknown

type Bbb = ThisParameterType<Cls["method"]>;
// Bbb = unknown -- WHY? How to distinguish?

Playground link

Screen Shot 2022-07-10 at 1 22 10 AM

🔍 Search Terms

method property from a bound callback property this

💻 Use Cases

I want to enumerate all plain properties of some type (e.g. a class instance), but skip methods. Currently I do it with:

export type NonMethodPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];

export type NonMethodProperties<T> = Pick<T, NonMethodPropertyNames<T>>;

but unfortunately, this NonMethodProperties also skips callback properties. E.g. in this example:

class Cls {
  constructor(public a = 10, public callback: () => void) {}
  method() {}
}

...I would expect NonMethodProperties<Cls> to return { a: number; callback: () => void }, but unfortunately it skips not only method, but also callback since I couldn't find a way to distinguish them.

@MartinJohns
Copy link
Contributor

The method in your class don't have a this argument, so ThisParameterType<> does not work on them. There's the open issue #28548 to automatically add a this argument to class methods.

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Jul 11, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow or the TypeScript Discord community.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants