typescripttslintjavascript-namespaces

TypeScript: Substitute Namespaces with something else


TSLint complains that namespaces shouldn't be used and as far as I understand the common sense is that they shouldn't be used anymore as they are special TypeScript construct.

So, I have a simple Timestamp interface:

export interface Timestamp {
  seconds: number | Long;
  nanos: number;
}

Due to the lack of static functions in interfaces, I use namespaces to organize that functionality, like this:

export namespace Timestamp {
  export function now(): Timestamp {
    ...
  }
}

How would you model that now without a namespace? The following construct looks ugly, is there another way?

export const Timestamp = {
  now: () => {
    ...
  }
}

Solution

  • So, I checked lib.es6.d.ts and it looks like a "const object" is really the way to go:

    interface DateConstructor {
        ...
        now(): number;
        ...
    }
    
    declare const Date: DateConstructor;
    

    Interestingly, the following construct also works and I would consider that as the "clean" approach:

    export interface Timestamp {
      seconds: number | Long;
      nanos: number;
    }
    
    export class Timestamp {
      public static now(): Timestamp {
        ...
      }
    }