11

I have a helper class with some static methods:

export default class MyHelper {
    private constructor() {}
    private static privateMethod() {}
    public static publicHelperMethod() {}
}

I have a React component that uses publicHelperMethod and I want to ensure that this specific method is passed in my props declaration.

The way I have attempted to this is:

type LoggerMethod = MyHelper.publicHelperMethod;

But this throws an error and says MyHelper is being used as a namespace.

I can make the class itself a type:

type Helper = MyHelper;

But I'm only interested in my logger method (the public helper in this abstraction).

Is it possible to make a method of a class a type? If so, what is the syntax for this?

Or, am I going about this entirely the wrong way?

3
  • 1
    I'm not sure I've seen this - using a specific function as type. Normally, you'd make a function interface and declare that your specific function implements the interface, so you are allowed to use it. It makes more sense when modelling things, since you can then change which function you call but maintain the type. Commented Oct 11, 2019 at 10:27
  • 1
    Although, with that said, I'm not sure you can note behaviour as part of the function interface. So, you could say that you have a sorter interface that takes two values and returns a number, but function multiply(a, b) { return a * b } also matches that signature, yet it isn't fit for sorting. So, it's not like the function interface solves your type problems. Commented Oct 11, 2019 at 10:29
  • 1
    Yeah, you will be able to capture the type of the function, which is just () => void, or maybe (this: typeof MyHelper) => void, but there's no way to represent a particular function of that type. That is, there are no "function literal" types. Commented Oct 11, 2019 at 16:11

1 Answer 1

14

If you want to use the type of the method:

type LoggerMethod = typeof MyHelper.publicHelperMethod;

If you want to use the implementation of the method:

const loggerMethod = MyHelper.publicHelperMethod;
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct. FYI (for your information) if you only want the return type of the function use the in-built type ReturnType<>. Example: type MyFunctionType = ReturnType<typeof MyHelper.publicHelperMethod>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.