using a class expression value as a type

Typescript has two name spaces, a value space and a type space (read more here). A class declaration adds a name in both value space and type space in the context where it is declared. A class expression, only adds these in the class scope. So you can use BarExpression as both the constructor and the type inside the class.

const Bar = class BarExpression {
  bar: BarExpression // Valid in the class
  constructor(x: BarExpression) { = x

In the enclosing scope, you are only left with the const named Bar that you can use as the constructor, but the type in not added to the enclosing scope ( const declaration has no reason to add a type to the enclosing scope).

You can get the instance type of a constructor using the InstanceType conditional type. And you can also add a type alias declaration, in order so get a similar effect to a class declaration:

const Bar = class Bar {
  bar: string
  constructor(x: string) { = x
type Bar = InstanceType<typeof Bar>
let a : Foo = new Foo(42)
let b : Bar = new Bar("hello")

Playground Link

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top