Search code examples
typescriptglobal-variables

Creating a unique id in typescript class


  • I can assign a unique index to a python class data member like here.
  • Is there an equivalent in typescript?
class Person
{
    index: number
    age: number
    name: string

    constructor(age: number, name: string)
    {
        // this.index = fresh index every time 
        this.age = age;
        this.name = name;
    }
}

Solution

  • As you figured out, there is no built-in mechanism for auto-incrementing class instance index feature.

    As the previous answers and comment suggest, a possible solution, common in OOP, is to use a static counter, and incrementing it in the class constructor.

    JavaScript/TypeScript being not necessarily OOP, like Python, another typical solution is also to use a closure (instead of the static counter):

    let counter = 0; // In closure of Person class
    
    class Person {
        index: number
        age: number
        name: string
    
        constructor(age: number, name: string) {
            this.index = counter++;
            this.age = age;
            this.name = name;
        }
    }
    
    var p1 = new Person(55, "moish");
    var p2 = new Person(74, "uzi");
    console.log(p1); // index 0
    console.log(p2); // index 1
    

    Playground Link


    A common factorization is to separate this auto-incrementing index feature into a base class:

    let counter = 0; // In closure of WithAutoIncrementedIndex class
    
    class WithAutoIncrementedIndex {
        index: number;
    
        constructor() {
            this.index = counter++;
        }
    }
    
    // All classes that extend WithAutoIncrementedIndex will have
    // the auto-incrementing index feature,
    // but sharing the same counter
    class Person extends WithAutoIncrementedIndex {
        age: number
        name: string
    
        constructor(age: number, name: string) {
            super(); // Call the parent constructor
            this.age = age;
            this.name = name;
        }
    }
    
    var p1 = new Person(55, "moish");
    var p2 = new Person(74, "uzi");
    console.log(p1); // index 0
    console.log(p2); // index 1
    

    Playground Link


    BTW, in your constructor, you do not need to explicitly assign your class members if they are already used as constructor parameters with the same name and a visibility modifier, see Class Parameter Properties:

    TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly.

    So you can do directly:

    class Person extends WithAutoIncrementedIndex {
        constructor(public age: number, public name: string) {
            super(); // Call the parent constructor
        }
    }
    

    Playground Link