As part of a semi-educational side project I am currently developing, there is a TypeScript interface
which specifies the presence of an id
property on any object that implements it. Throughout this application, you will often find arrays Array<>
containing these objects that adhere to the IIdable
interface.
One challenge I'm facing is the lack of a database in this application. I am exploring ways to implement an auto-increment feature within the service that manages these lists of IIdable
objects. At first, I considered extending the functionality in a typical "JavaScript" manner like so...
Array<MyProject.Models.IIdable>.prototype.getNextId = () => {
let biggestId: number = 0;
for (let current of this) {
if (current.id > biggestId)
biggestId = current.id;
}
return biggestId + 1;
};
...However, Visual Studio Code raised some errors during implementation, one of them being:
Cannot find name 'prototype'
This is puzzling as Array<T>
is considered a JavaScript primitive type and everything in JavaScript is treated as an object. This brings up the issues that TypeScript was designed to address or avoid. Admittingly, my knowledge in both JavaScript and TypeScript may be limited enough to lead me into making foolish decisions.
If I were working in C# - a language distinct from TypeScript - I would approach creating such an extension method differently, perhaps something like this:
public static GetNextId(this List<IIdable> source)
{
// ...Logic to determine the next ID value.
}
Regrettably, I am uncertain if this can be executed here. Before reaching out with this question, I researched how to write extension methods in TypeScript. One suggestion involved modifying the interface of the host type with the new method, a solution that might not work in this context. My goal is to create an extension exclusively for cases involving an Array<IIdable>
, leaving all other scenarios untouched.
Hence, the burning inquiry remains: How can I craft an extension method targeting a specific datatype within a generic type in TypeScript?