How can I return a class from a TypeScript function? How can I return a class from a TypeScript function? typescript typescript

How can I return a class from a TypeScript function?


Quick answer

change this:

export let factory = () => {    return class Foo {}};

to that:

export let factory = () : any => {    return class Foo {}};

Longer answer

This error could be triggered/forced by to a tsconfig.json setting:

{    "compilerOptions": {        ...        "declaration": true // this should be false or omitted

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

let factory = () => { ...

it must start to guess what is the return type, because that information is missing (check the : <returnType> placeholder):

let factory = () : <returnType> => { ...

in our case, TS will quickly find out, that the returned type is easy to guess:

return class Foo {} // this is returned value,                     // that could be treated as a return type of the factory method

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:

export class Foo {} // Foo is exportedexport let factory = () : Foo => { // it could be return type of export function    return Foo};

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:

export let factory = () : any => {    return class Foo {}};

But even better would be to have some public interface

export interface IFoo {}

And then use such interface as return type:

export let factory = () : IFoo => {    return class Foo implements IFoo {}};


I think this is a proper way to do it:

export let factory = () => {     class Foo {/* ... */}     return Foo as (new () => { [key in keyof Foo]: Foo[key] })};

Check it out on playground


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

export class Foo {}; export let factory = () => {    return Foo;};

With ES6 you don't need to export the class type, but with TypeScript you absolutely should exporting the type signatures.