Bidoubiwa
Bidoubiwa

Reputation: 960

Best way to export both class and types in TypeScript

Following this stackoverflow question (~2016) and the official documentation of typescript about Class modules

It is stated that class module declaration file should use namespace the following way:

export = MyClass;

declare class MyClass {
    constructor(someParam?: string);

    someProperty: string[];

    myMethod(opts: MyClass.MyClassMethodOptions): number;
}

declare namespace MyClass {
    export interface MyClassMethodOptions {
        width?: number;
        height?: number;
    }
}

If I apply this documentation onto my project this my linter screams at me with the no-namespace rule (doc about this rule):

ES2015 module syntax is preferred over custom TypeScript modules and namespaces.eslint@typescript-eslint/no-namespace Peek Problem (⌥F8)

and also

MyClass is already defined

Is this still the preferred way to handle types in Class modules?

Edit It is important that the class remained exported by default

Solution

import myClass from 'myclass.ts'

export default myClass

export interface myObject {
...
}

Upvotes: 1

Views: 3265

Answers (1)

Francesc Montserrat
Francesc Montserrat

Reputation: 349

You can export the class and interface on their own, without namespace:

export interface MyClassMethodOptions {
  width?: number;
  height?: number;
}

export default class MyClass {
  constructor(someParam?: string);

  someProperty: string[];

  myMethod(opts: MyClassMethodOptions): number;
}

Upvotes: 2

Related Questions