I have a function that provides a basic functionality like this one:
// File 1: Core function
export const extensions = [];
export interface ResultInterface {
fullname:string,
age:number
}
function maFunction():ResultInterface {
var o = {
fullname:"alex",
age:21
};
extensions.forEach((extension) => o = extension(o));
return o;
}
As you can see from the code above the maFunction
is extensible by looking through the extensions
array and applying those functions.
For example, one can install the following extensions through NPM:
// File 2: Extensions 1 (installed via NPM)
extensions.push(function (o) {
o.ageInMonths = o.age * 12;
return o;
});
// File 3: Extensions 2 (installed via NPM)
extensions.push(function (o) {
o.firstname = o.fullname.split(" ")[0];
o.lastname = o.fullname.split(" ")[1];
});
Now in the userland:
// File 4: Userland execution
var myVar = maFunction();
myVar.ageInMonths // error: Property 'ageInMonths' does not exist on type 'ResultInterface'.
myVar.firstname // error: Property 'firstname' does not exist on type 'ResultInterface'.
myVar.lastname // error: Property 'lastname' does not exist on type 'ResultInterface'.
I didn't expect typeScript to be smart enough to detect the properties added via the extensions. But how can each extension add them manually? how can each extension extend the ResultInterface
and add it's own properties?