I recently started using typescript and encountered an issue while working on a problem. I initially created the following class:
export class ModuleInfoContainer extends Array<ModuleInfo> {
constructor() {
super();
}
search(id: number) {
let k: ModuleInfo;
this.every(a => {
k = a.search(id);
return !k;
});
return k;
}
}
Despite my expectations, during debugging I found that all array functions were accessible except for the member function search
of ModuleInfoContainer
. After some research online, I came across an example which led me to modify the code as follows:
export class ModuleInfoContainer extends Array<ModuleInfo> {
constructor() {
super();
}
search = function (id: number) {
let k: ModuleInfo;
this.every(a => {
k = a.search(id);
return !k;
});
return k;
};
}
This modification resolved the issue and the code worked as anticipated.
What was wrong with the first code?
EDIT: ModuleInfo
class
export class ModuleInfo {
Id: number;
Name: string;
DisplayName: string;
ChildModules: ModuleInfoContainer;
DependsOn: ModuleInfo[];
parent: ModuleInfo;
search(id: number): ModuleInfo {
if (this.Id === id) {
return this;
} else if (this.ChildModules && this.ChildModules.length) {
return this.ChildModules.search(id);
}
return undefined;
}
}
This is how I attempted to call the search function:
let k = new ModuleInfoContainer();
k.search(1);
The typescript compilation was successful, but at runtime, an error occurred stating that
k does not have a member function named search
(the error message might vary slightly, but the essence remains the same). However, the second code snippet worked correctly.