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;
}
}
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
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
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
, orreadonly
.
So you can do directly:
class Person extends WithAutoIncrementedIndex {
constructor(public age: number, public name: string) {
super(); // Call the parent constructor
}
}