打字稿:类中的扩展集会导致错误(构造函数集需要“新”) [英] Typescript: Extending Set in class causes error (Constructor Set requires 'new')
本文介绍了打字稿:类中的扩展集会导致错误(构造函数集需要“新”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对Set对象执行一些基本操作,例如此处
I'm trying to implement some basic operations to the Set object like says here
这是代码
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
推荐答案
如果要向其中添加函数Set原型,或向Set添加polyfills,您可以执行以下操作:
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;
}
要使用:
stringSet = new Set<string>()
stringSet.isSuperset(someOtherSet);
stringSet.someNewFunc(); // returns true
这篇关于打字稿:类中的扩展集会导致错误(构造函数集需要“新”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文