Typescript: Extending Set in class causes error (C

2019-07-09 05:04发布

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

1条回答
地球回转人心会变
2楼-- · 2019-07-09 05:17

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
查看更多
登录 后发表回答