TypeScript static members vs namespace with class name

Viewed 1556

In TypeScript, I have been separating non-instance variables out of my classes and into a namespace with the same name as the class. For example:

class Person
{
    age: number;

    constructor(age: number)
    {
        this.age = age;
    }
}

namespace Person
{
    export let numberOfFingers: number = 10;
}

export default Person;

as opposed to this:

class Person
{
    static numberOfFingers: number = 10;

    age: number;

    constructor(age: number)
    {
        this.age = age;
    }
}

export default Person;

Is there any benefit to either of these methods?

1 Answers

As far as typechecking and code generation is concerned, both methods produce exactly the same results. I can offer two not very strong arguments in favor of static members:

  • it's the most obvious thing to do, it does not require knowledge of advanced parts of the language (declaration merging) to understand the code

  • if you ever need to have a function that creates and returns class definition (as described for example here, to simulate static generic member or to add a mixin), then namespaces will not work - you can't have namespace inside a function.

Related