I’m using TypeScript with a dependency injection library which works very similar to Angular 1 – basically: register a factory with your dependencies as arguments.
This is how I would register a class in ES6
export let factory = () => {
return class Foo {}
};
If I write the same in TypeScript:
export let factory = () => {
return class Foo {}
};
It fails to compile with the error
error TS4025: Exported variable ‘factory’ has or is using private name ‘Foo’.
Is there any way to allow TypeScript to return a class from a factory function?
You need to export the class as well so that the consumer of the method can access the type.
Typically a factory will return an instance rather than a class or constructor.
UPDATED EXAMPLE
With ES6 you don’t need to export the class type, but with TypeScript you absolutely should exporting the type signatures.
I was struggling with the same error. The solution for me was to remove the
from
tsconfig.json
or to set it tofalse
.I’ve found separately provided solution satisfying:
Given that signature I can use
MyClassRef
as a type of return value:Quick answer
change this:
to that:
Longer answer
This error could be triggered/forced by to a tsconfig.json setting:
But that is not the reason, it is just a trigger. The real reason (as discussed here Error when exporting function that returns class: Exported variable has or is using private name) comes from the Typescript compiler
when TS compiler founds statement like this
it must start to guess what is the return type, because that information is missing (check the
: <returnType>
placeholder):in our case, TS will quickly find out, that the returned
type
is easy to guess:so, in case we would have that similar statement (this is not the same, as original statement at all, but let’s just try to use it as an example to clarify what happens) we can properly declare return type:
that approach would be working, because the
Foo
class is exported, i.e. visible to external world.Back to our case. We want to return type which is not exported. And then, we MUST help TS compiler to decide, what is the return type.
It could be explicit any:
But even better would be to have some public interface
And then use such interface as return type:
I think this is a proper way to do it:
Check it out on playground
Are you looking for returning Type of class from the function? Below is one code snippet how we can implement factory in TypeScript similar to in other languages.
Late answer on old question:
You need to have the class defined outside the factory method and define return value using ‘typeof’.