0

I have the following TypeScript code:

class ClassA {
  field1: any;
}

const SomeClassAsA = diContainer.get('SomeClass') as ClassA;

class ClassB extends ClassA {} // works
class ClassB extends SomeClassAsA {} // error: Type ClassA is not a constructor function type

Why can ClassB be extended with ClassA but not with some other Object casted as ClassA? In need to extend SomeClass. How can I accomplish that?

I use TypeScript 1.5.3

2
  • 1
    ClassA is a class. SomeClassAsA is a constant with type ClassA Commented Jan 3, 2020 at 18:46
  • Okay, that makes kind of sense. Now I know the WHY. But HOW do I solve the problem? Commented Jan 3, 2020 at 18:49

1 Answer 1

1
const SomeClassAsA = diContainer.get('SomeClass') as typeof ClassA;
//                                                   ^ added

When you use a class as a type, you are actually typing an instance of that class. Remember, that a class is a real object in javascript, not like an interface which has no raw javascript corollary.

This makes sense, because it allows you to write:

const person: Person = new Person()

person is clearly and an instance of Person and not the class constructor object Person.

So to get the the type of the class itself, use the typeof operator.

Working playground

Sign up to request clarification or add additional context in comments.

Comments

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.