打字稿:括号符号属性访问 [英] Typescript: bracket notation property access

查看:25
本文介绍了打字稿:括号符号属性访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用这样的括号表示法访问类型化对象:

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 

根据规范 4.10我明白了,这是一种预期的行为:

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.

我的用例是对象缩小,如

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

推荐答案

obj[x] 中不使用变量,你可以写:

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

obj["bar"].sort

此处使用变量的唯一原因是从 IFoo 接口中选择任意属性.你好像只有一个.如果您的 IFoo 上有许多字符串数组,您可以将其设为可索引并写入:

The only reason to use a variable here is to choose an arbitrary property from your IFoo interface. You seem to only have one. If you had many string arrays on your IFoo, you could make it indexable and write:

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;

这篇关于打字稿:括号符号属性访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆