Typescript: access to record notation in parentheses

I would like to access the typed object using brackets:

interface IFoo {
    bar: string[];
}

var obj: IFoo = { bar: ["a", "b"] }
var name = "bar";
obj[name]. // type info lost after dot 

According to specification 4.10, as I understand it, this is the 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 this is the case and is it possible to circumvent this behavior?

Edit: My use case with minimizing objects 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)
}
+10
source share
2 answers

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

obj["bar"].sort

- IFoo. , , . IFoo , :

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

:

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

:

obj["some new property"] = ["a", "b"];
obj["some new property"].sort;
+5

, ..

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

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

. ,

+1

Source: https://habr.com/ru/post/1623806/


All Articles