简体   繁体   中英

How to extend from native constructor typescript

class ExtendSet<T> extends Set<any> {
  constructor(value: any) {
    super(value);
  }
}

var s = new ExtendSet([1, 2, 3, 4, 5]);

console.log(s);

TypeError: Constructor Set requires 'new'

actually, I just want to extend Set Object some method,like toArray():any[]

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "moduleResolution": "node",
    "sourceMap": true,
    "types": [
      "mocha",
      "node",
      "typescript",
      "core-js"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

I am not sure why you are getting this error. If you go to this playground snippet you'll see that it throws no error. Perhaps you are using an outdated version of typescript.

As to the thing you are trying to achieve:

I just want to extend Set Object some method,like toArray():any[]

An easier way would be to do the following:

interface Set<T> { 
    toArray: () => any
}

Set.prototype.toArray = () => { 
    // write your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM