3

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 Answer 1

1

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.

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.