Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: bracket notation property access

Tags:

typescript

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) } 
like image 762
AndrewSokolowski Avatar asked Jan 11 '16 17:01

AndrewSokolowski


People also ask

How do you access object properties dynamically using bracket notation in TypeScript?

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] .

Under what circumstances would you need to use bracket notation to access a value in an object?

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.

How do you use bracket notation?

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.

How do you check if an object has a property in TypeScript?

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.


1 Answers

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

like image 187
Sonic Soul Avatar answered Oct 20 '22 23:10

Sonic Soul