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) }
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
We must use bracket notation whenever we are accessing an object's property using a variable or when the property's key is a number or includes a symbol or is two words with a space.
Bracket notation is another way to access a property of an object. To use bracket notation, write the name of the object, followed by brackets [] . Inside the brackets, write the property name as a string. Bracket notation, unlike dot notation, can be used with variables.
To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With