typescript 打字稿:括号符号属性访问

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34727936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:52:17  来源:igfitidea点击:

Typescript: bracket notation property access

typescript

提问by AndrewSokolowski

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 spec4.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)
}

采纳答案by mk.

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 IFoointerface. You seem to only have one. If you had many string arrays on your IFoo, you could make it indexable and write:

在这里使用变量的唯一原因是从您的IFoo界面中选择任意属性。你好像只有一个。如果您的 中有许多字符串数组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;

回答by Sonic Soul

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

效果很好。如果我找到缩短它的方法,我会更新