首页 文章

使用动态键扩展Object的Typescript接口

提问于
浏览
2

在Typescript中,当使用索引器时,我无法使我的接口扩展Object(键作为字符串) .

如果我不扩展Object然后它工作正常,但intellisense不提供Object.hasOwnProperty()方法的建议 .

interface MyObject extends Object {
 [key: string] : string;
}

在上面的代码中,我得到编译时错误:“类型为'(v:string)=> boolean'的属性'hasOwnProperty'不能赋予字符串索引类型'string' . ”

稍后在代码中我想使用MyObject类型的变量来检查它是否包含使用Object的hasOwnProperty方法的特定键 .

1 回答

  • 2

    您无需扩展 Object 即可拥有 hasOwnProperty 方法 . 由于所有对象都继承 Object ,因此该方法将存在于任何接口实例上 .

    interface MyObject {
        [key: string]: string;
    }
    
    var v: MyObject = {
        "foo" : "1"
    }
    v.hasOwnProperty("foo");
    

    索引签名通常意味着接口的所有成员都将与索引的返回类型兼容 . 你可以使用union类型解决这个问题,但是如果没有 Object.assign ,你仍然无法直接创建这样的对象:

    type MyObject  = Object & { // Object is useless but we can specify it
        [key: string]: string;
    } & { // We can specify other incompatible properties
        required: boolean
    }
    
    // We can create an instance with `Object.assign`
    var v: MyObject = Object.assign({
        "foo" : "1"
    }, {
        required: true
    });
    v.hasOwnProperty("foo");
    console.log(v.required);
    console.log(v['bar']);
    

相关问题