Home Typescript: bracket notation property access

# Typescript: bracket notation property access

AndrewSokolowski
1#
AndrewSokolowski Published in 2016-01-11 17:50:15Z
 I'd like to access typed object with bracket notation like this: interface IFoo { bar: string[]; } var obj: IFoo = { bar: ["a", "b"] } var name = "bar"; obj[name]. // type info lost after dot  According to the spec 4.10 as far as I understood it, it is an expected behavior: A bracket notation property access of the form ObjExpr [ IndexExpr ] .... Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.  Can anyone confirm if that is true and if it is possible to circumvent this behavior. Edit: My use case is with object minification as in var props = {long_name: "n"}; var shortName = props.long_name; function(minObj) { var value = minObj[shortName] var newMinObj = {}; newMinObj[shortName] = value.toUpperCase(); db.save(newMinObj) } 
mk.
2#
 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;