2

I have a class that I want to extend with a factory class that will return the correct class based on the input.

class Base<S> {
  prop: S;
  base() { }
}

class A<S> extends Base<S> {
  a() { }
}

class B<S> extends Base<S> {
  b() { }
}


interface TypeA {
  propA: any;
}

interface TypeB {}

function isTypeA(params: TypeA | TypeB): params is TypeA {
  return (params as TypeA).propA !== undefined;
}

function factory(params: TypeA): typeof A;
function factory(params: TypeB): typeof B;
function factory(params: TypeA | TypeB): typeof A | typeof B {
  if (isTypeA(params)) {
    return A;
  } else {
    return B;
  }
}

const param: TypeA = { propA: {} };
const param2: TypeB = {};

class Test extends factory(param) { }

In addition to that, I need to pass a generics all the way up. How can I pass the generic from the factory function to the Base class?

0

1 Answer 1

2

Do this:

class Test<T> extends factory(param)<T> { }

Or, if you don't want Test to be generic:

class Test extends factory(param)<string>()
Sign up to request clarification or add additional context in comments.

3 Comments

I think the point is that factory should return typeof A<typeof param> which is syntactically incorrect in typescript, but that is the desired effect. ie class Test extends factory(param)<typeof param> { }
You think so? I didn't understand it that way. I think that the type of param and the type parameter of A (or B) are not related, but of course, he/she can clarify that
I might have misunderstood, OP should clarify :)

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.