0

I have an interface and a class:

interface Widget {
  widgetStuff(): void;
}

class Foo implements Widget {
  widgetStuff(): void {
  }
}

I want to track all of the Widgets in another class, and an index signature seems to be the easiest way:

class WidgetCatalog {
  private readonly mapping: { [key: string]: Widget };

  constructor() {
    this.mapping = {
      Foo // <= Error here
    }
  }
}

I'm getting this error: error TS2322: Type 'typeof Foo' is not assignable to type 'Widget'. Property 'widgetStuff' is missing in type 'typeof Foo'.

I'm not sure what Im missing here, since it seems to be a pretty straightforward implementation. Do I need to specify the value type in the index signature differently?

1
  • 2
    this.mapping.Foo will be Foo, the class constructor that makes new Widgets. It's not a Widget itself. So either mapping should hold Widget constructors, in which case it's mis-annotated, or this.mapping should be initialized to {Foo: new Foo()} or something. Commented Oct 3, 2019 at 19:34

1 Answer 1

1

@jcalz pointed me in the right direction. This version works:

interface Widget {
  widgetStuff(): void;
}

class Foo implements Widget {
  widgetStuff(): void {
  }
}

class WidgetCatalog {
  // Change to mapping of Widget constructors
  private readonly mapping: { [key: string]: new(...args) => Widget };

  constructor() {
    this.mapping = {
      Foo
    }
  }
}
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.