【问题标题】:Typescript: bracket notation property access打字稿:括号符号属性访问
【发布时间】:2016-04-16 03:21:21
【问题描述】:

我想访问带有括号符号的类型对象,如下所示:

interface IFoo {
    bar: string[];
}

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

据我了解,根据spec 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.

任何人都可以确认这是否属实以及是否可以规避这种行为。

编辑: 我的用例是对象缩小,如

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我将其添加为单独的界面,因为我需要保持原始..

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

    并在需要时引用它

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

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

    【讨论】:

    • 太棒了!我将其设为通用以保持类型安全:export interface IIndexable<T = any> { [key: string]: T }
    【解决方案2】:

    而不是在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;
    

    【讨论】:

    • 但是如果 IFoo 有不同类型的属性就不行了,对吧?
    • 很抱歉打扰您,但我已经用一个潜在的用例更新了原始问题。似乎没有通用方法可以让 typescript 知道 shortName 是并且总是将是一个字符串“n”。
    • 这将是一个相当复杂的推论(在大多数情况下它不起作用,在其他情况下它不会有用)。 TypeScript 不执行它。通常,用某种语言以某种方式做事的无能或困难表明用该语言做事的方式不好(至少因为人们不熟悉它,尽管它通常实际上不合适而且是个坏主意) .
    • 如果你想拥有不同的类型,你可以使用union。在该示例中,您可以将索引定义为以下[key: string]: string[] | your_second_type;
    • 弄清楚如何为键通用 this guide 设置类型确实很有帮助,以展示如何使用 keyof
    猜你喜欢
    • 2017-02-05
    相关资源
    最近更新 更多