Typescript: bracket notation property access
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
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;