2

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?

Alex C.
  • 4,021
  • 4
  • 21
  • 24

1 Answers1

0

I don't think is it possible to do this without modifying the .d.ts of ResultInterface (see so response here: Extend interface defined in .d.ts file)

What you could do tho' is use Intersection types to type myVar and augment it's interface with the functions you need:

var myVar: ResultInterface & {ageInMonths: number, firstname: string, lastname: string} = maFunction();

You could add a "type shortcut" like this:

type ResultInterfaceAugmented = {ageInMonths: number, firstname: string, lastname: string}& ResultInterface;
var myVar: ResultInterfaceAugmented = maFunction();
Community
  • 1
  • 1
dekajoo
  • 2,024
  • 1
  • 25
  • 36