[英]Typescript: bracket notation property access
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: 据我所知,根据规范 4.10,它是一种预期的行为:
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)
}
Instead of using a variable in obj[x]
, you can write : 您可以编写 :而不是在
obj[x]
中使用变量
obj["bar"].sort
The only reason to use a variable here is to choose an arbitrary property from your IFoo
interface. 在这里使用变量的唯一原因是从
IFoo
接口中选择任意属性。 You seem to only have one. 你似乎只有一个。 If you had many string arrays on your
IFoo
, you could make it indexable and write: 如果你的
IFoo
上有很多字符串数组,你可以使它成为可索引的并写:
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;
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
如果我找到缩短它的方法,我会更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.