将有效Javascript dict函数的Typescript字典编码到类中

将有效Javascript dict函数的Typescript字典编码到类中,javascript,dictionary,typescript,Javascript,Dictionary,Typescript,从“effectivejavascript”dict示例中的示例派生出一个好的Typescript类是什么 功能指令(要素){ //允许一个可选的初始表 this.elements=elements | |{};//简单对象 this.hasSpecialProto=false;//是否有“\uuuuu proto\uuuuuuu”键? this.specialProto=未定义;//“\uuuuu proto\uuuuuu”元素 } Dict.prototype.has=功能(键){ 如果(

从“effectivejavascript”dict示例中的示例派生出一个好的Typescript类是什么

功能指令(要素){
//允许一个可选的初始表
this.elements=elements | |{};//简单对象
this.hasSpecialProto=false;//是否有“\uuuuu proto\uuuuuuu”键?
this.specialProto=未定义;//“\uuuuu proto\uuuuuu”元素
}
Dict.prototype.has=功能(键){
如果(键==“\uuuuu proto\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu{
返回此.hasSpecialProto;
}
//只拥有财产
返回{}.hasOwnProperty.call(this.elements,key);
};
Dict.prototype.get=函数(键){
如果(键==“\uuuuu proto\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu{
返回此.specialProto;
}
//只拥有财产
返回此。has(键)
?此项。要素[关键]
:未定义;
};
Dict.prototype.set=功能(键,val){
如果(键==“\uuuuu proto\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu{
this.hasSpecialProto=true;
this.specialProto=val;
}否则{
this.elements[key]=val;
}
};
Dict.prototype.remove=功能(键){
如果(键==“\uuuuu proto\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu{
this.hasSpecialProto=false;
this.specialProto=未定义;
}否则{
删除此。元素[键];
}
};

机器人想要我输入更多的解释,我认为这是冗长的。谁知道我什么时候能打出足够的字来取悦它。它还希望我能完美地缩进东西。

假设您的原始代码是正确的。以下是转换为TypeScript的代码:

class Dict {
    hasSpecialProto = false; // has "__proto__" key?
    specialProto = undefined; // "__proto__" element

    constructor(public elements = {}) {
        // allow an optional initial table        

    }

    has(key) {
        if (key === "__proto__") {
            return this.hasSpecialProto;
        }
        // own property only
        return {}.hasOwnProperty.call(this.elements, key);
    }

    get(key) {
        if (key === "__proto__") {
            return this.specialProto;
        }
        // own property only
        return this.has(key)
            ? this.elements[key]
            : undefined;
    }

    set(key, val) {
        if (key === "__proto__") {
            this.hasSpecialProto = true;
            this.specialProto = val;
        } else {
            this.elements[key] = val;
        }
    }

    remove(key) {
        if (key === "__proto__") {
            this.hasSpecialProto = false;
            this.specialProto = undefined;
        } else {
            delete this.elements[key];
        }
    }
}
注意,TypeScript将知道函数中的
这是什么意思,我在构造函数中使用了一个默认参数


如果您正在寻找更强大(且经过测试)的泛型,请查看TypeScript集合:

我会向方法中添加返回值类型,因为如果没有它,返回值的类型将是
void
,如果从TypeScript调用,则不会编译:
var hasTest:boolean=dict.has(“测试”)我知道你提到的那本书,但是你能详细解释一下他们为什么对
\uuuuu proto\uuuu
这样做吗?此处所示的prototype属性不应该以这种方式访问,应该避免这样的使用。我指的是ES规范。获取prototype链接的唯一方法是调用
Object.getPrototypeOf(obj)
。这本书来自《有效的JS》,第122页,“使用字典类来防止使用“proto”作为键”;“提示45”的结尾。啊哈,好吧,这是关于保护proto的,这和我说的有道理,谢谢!(我手边没有这本书)