Natasha
Natasha

Reputation: 441

Factory functions that return classes (= class constructors) in TypeScript

If I define a class in the following way in TypeScript

class A {}

then A is both a value and a type, so I can use it in both ways:

type B = A
const C = A

If A would be the result of a fancy class factory function instead:

const A = fancyClassFactory(...someArgs)

then A is only a value, NOT a type ...

Are there any ways to use such a class factory function and also get the type of the class?

Many thanks in advance.

Upvotes: 4

Views: 1391

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249666

Assuming A is the constructor to the class you can use the InstanceType conditional to get the type of the instance:

const A = fancyClassFactory(...someArgs)
type A = InstanceType<typeof A>

For the specific example @daniel-hilgarth provided you could use conditional types so the return type is different according to the passed in constant:

function fancyClassFactory<T extends 'a' | 'b'>(what: T) : (T extends 'a' ? typeof fancyClassFactory.A: typeof fancyClassFactory.B) 
function fancyClassFactory(what: string) {
    if (what === 'a') {
        return  fancyClassFactory.A
    }
    if (what === 'b') {
        return fancyClassFactory.B
    }
}

namespace fancyClassFactory {
    export class A {
        foo() { return 'barA'; }
    }
    export class B {
        bar() { return 'fooB'; }
    }
} 
const A = fancyClassFactory('a');
const B = fancyClassFactory('b');
type TA = InstanceType<typeof A>;

function generic<T>(t: T) {
    console.log(t);
}

generic<TA>(new A());
generic<TA>(new B());

Upvotes: 2

Related Questions