Adithya Reddy Adithya Reddy - 1 month ago 4
TypeScript Question

How does TypeScript know about the behaviour of the length field in custom array types?

When you create a custom array type using an interface, and give it the field

length: number
, TypeScript seems to somehow calculate the length of the array by itself, but if you leave the field out of the custom type definition, it no longer works.

What exactly is going on in the background here?

My code is:

interface IPerson {
fullName: string;
age: number;
}

class Person implements IPerson {
fullName: string;
age: number;

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

interface IPersonArray {
[index: number]: IPerson;
length: number;
}

var personArray: IPersonArray = [new Person("Jane", 21),
new Person("John", 22)];

for (var i = 0; i < personArray.length; i++) {
console.log(personArray[i].fullName);
}


Here's the most relevant part:

interface IPersonArray {
[index: number]: IPerson;
length: number;
}

var personArray: IPersonArray = [new Person("Jane", 21),
new Person("John", 22)];

for (var i = 0; i < personArray.length; i++) {
console.log(personArray[i].fullName);
}


I'm only declaring the
length
field in the interface, but TypeScript magically figures out how the length field is supposed to work, and I get the output as expected. How does this happen?

Answer

This isn't as magical as it might seem.

You add the definition for that field yourself in the interface IPersonArray, then you assign an array to personArray. TypeScript knows that an array has a length property, so the assignment is ok. And in run-time, the length-property of the array is called.

If you leave length out from your interface/type, you will not be able to access it, just like you can't access any of the other properties of the array that you happen to assign personArray.