Search code examples
javascriptangulartypescriptecmascript-5

Typescript: Extending Set in class causes error (Constructor Set requires 'new')


I'm trying to implement some basic operations to the Set object like says here

This is the code

export class Conjunto extends Set<any>{
  constructor(initialValues?) {
    super();
    return new Conjunto(initialValues);
  }

  isSuperset(subset) {
    //some code
  }
}

Do you guys have any idea to make it work? or am I doing something wrong?

For the moment I'm using the hack this guy found here


Solution

  • if you are trying to add functions to the Set prototype, or add polyfills to Set, you can do the following:

    declare global {
      interface Set<T> {
          // polyfill
          isSuperset(subset: Set<T>) : boolean;
          // new function
          someNewFunc(): boolean;
      }
    }
    
    // add polyfill to the Set prototype as mentioned in the doc you provided: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Set 
    Set.prototype.isSuperset = function(subset) {
        for (var elem of subset) {
            if (!this.has(elem)) {
                return false;
            }
        }
        return true;
    }
    
    //add the new someNewFunc;
    Set.prototype.someNewFunc = function() {
        // some logic here...
        return true;
    }
    

    to use:

    stringSet = new Set<string>()
    stringSet.isSuperset(someOtherSet);
    stringSet.someNewFunc(); // returns true