Typescript interface with dynamic keys extending Object

11,939

You don't need to extend Object to have the hasOwnProperty method. Since all objects inherit Object this method will exist on any instance of the interface.

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

var v: MyObject = {
    "foo" : "1"
}
v.hasOwnProperty("foo");

The index signature generally means that all members of the interface will be compatible with the return type of the index. You can get around this using union types though, but you still can't directly create such an object without 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']); 
Share:
11,939
Indra Chatterjee
Author by

Indra Chatterjee

I currently write code in typescript to make HTML components which can be used in wallboard applications. I have programming knowledge with C, C++ , Java and Javascript.

Updated on June 19, 2022

Comments

  • Indra Chatterjee
    Indra Chatterjee about 2 years

    In Typescript I am not able to make my interface extend Object when indexer is used (key as string).

    If i do not extend Object then it works fine , but intellisense does not give suggestions for Object.hasOwnProperty() method.

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

    Above code, I get compile time error as: "Property 'hasOwnProperty' of type '(v: string) => boolean' is not assignable to string index type 'string'."

    Later in code i would like to use variable of type MyObject to check if it contains a particular key using hasOwnProperty method of Object.

  • Indra Chatterjee
    Indra Chatterjee over 6 years
    Thank you, this gives much clarity needed. Just that when i do "v.", in code i do not get hasOwnProperty in suggestion list. Is there a way around to that ?
  • Danielo515
    Danielo515 over 3 years
    This does not work. Which version of TS you tested this with?