gpt4 book ai didi

javascript - typescript :在类中扩展集会导致错误(构造函数集需要 'new' )

转载 作者:搜寻专家 更新时间:2023-10-30 21:51:28 25 4
gpt4 key购买 nike

我正在尝试对 Set 对象执行一些基本操作,如 here 所说

这是代码

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

isSuperset(subset) {
//some code
}
}

你们有什么想法让它发挥作用吗?还是我做错了什么?

目前我正在使用这个人发现的 hack here

最佳答案

如果您尝试向 Set 原型(prototype)添加函数,或向 Set 添加 polyfill,您可以执行以下操作:

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

关于javascript - typescript :在类中扩展集会导致错误(构造函数集需要 'new' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43301849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com