Typescript: bracket notation property access

后端 未结 2 1580
遥遥无期
遥遥无期 2020-12-17 09:57

I\'d like to access typed object with bracket notation like this:

interface IFoo {
    bar: string[];
}

var obj: IFoo = { bar: [\"a\", \"b\"] }
var name = \         


        
相关标签:
2条回答
  • 2020-12-17 10:09

    Instead of using a variable in obj[x], you can write:

    obj["bar"].sort
    

    The only reason to use a variable here is to choose an arbitrary property from your IFoo interface. You seem to only have one. If you had many string arrays on your IFoo, you could make it indexable and write:

    interface IFoo {
        bar: string[];
        bar2: string[];
        [key: string]: string[]; // IFoo is indexable; not a new property
    }
    

    Which would allow you to write:

    var name = "bar";
    obj[name].sort;
    

    But it would also allow you to write:

    obj["some new property"] = ["a", "b"];
    obj["some new property"].sort;
    
    0 讨论(0)
  • 2020-12-17 10:18

    I added it as a separate interface because i need to keep original..

    export interface IIndexable {
      [key: string]: any;
    }
    

    and referencing it when needed

    getEditDate(r: IRestriction, fieldName: string) {
        ...
        value={(r as IIndexable)[fieldName] as Date}
    

    works well. i will update if i find a way to shorten it

    0 讨论(0)
提交回复
热议问题