ollifant
ollifant

Reputation: 8616

Typescript error when using interface from module as field within class

I am working on providing a type definition file for fabric.js. The general structure is shown in the following sample:

declare module fabric {
   export interface Canvas {
      selectionBorderColor: string;
      selectionColor: string;
      ...
   }

   var Canvas: {
      new (): Canvas;
   }
}

This pattern allows me to use fabric.Canvas in a 'interface-like' way, so that variables are associated with the fabric.Canvas interface. At the same time it allows me to call "static members" (such as the constructor of fabric.Canvas).

But this leads to a problem when using a field of interface 'fabric.Canvas' within a class. The following sample shows such an case:

Typescript error when using interface from module as field within class

This problem only occurs when placing the interface within a module, otherwise everything works fine.

Any solutions for this problem?

Upvotes: 4

Views: 869

Answers (1)

Fenton
Fenton

Reputation: 251172

There is some type confusion because you have an interface and a field with the same name - I know this is common in the lib.d.ts file, but I don't think it is a good practice when writing new TypeScript code. It seems to be something of a necessity for defining existing code.

If you rename var Canvas to var MyCanvas (or anything else) your code works.

I tend to prefix my interfaces with an I, for example ICanvas - but this isn't a TypeScript convention (yet).

declare module fabric {
   export class Canvas {
      selectionBorderColor: string;
      selectionColor: string;
   }
}

class MyClass {
    canvas: fabric.Canvas;
}

Upvotes: 2

Related Questions