在TypeScript可索引接口中访问索引

时间:2014-07-09 11:29:34

标签: dictionary typescript

我使用索引类型在typescript中创建了一个“Dictionary”,并尝试将其用作for in语句中的数组。我能够毫无问题地获得值,但无法弄清楚我如何访问索引(参见for循环中的??)。

export interface Settings {
    dictionary : IDictionary[];
}

export interface IDictionary{
    [index: number]: string;
}

// To be used like this
for (var setting in Settings.dictionary)
{
  console.log(“Setting is: “ + setting + “ for id: “ + ??);
}

2 个答案:

答案 0 :(得分:1)

实际上,设置是ID。使用[id]

索引所需的值

详细了解for / in:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

答案 1 :(得分:1)

以下是您的代码的完整工作示例...基本上您的所有界面都是正确的,您只需在循环中调整该位,就像您使用???所示。

关键是setting

要获取该值,请使用settings.dictionary[setting]

以下是完整代码:

export interface Settings {
    dictionary : IDictionary[];
}

export interface IDictionary{
    [index: number]: string;
}

function logSettings(settings: Settings) {
    for (var setting in settings.dictionary) {
        console.log('Setting is: ' + settings.dictionary[setting] + 
            ' for id: ' + setting);
    }
}

var settings: Settings = {
    dictionary: []
};

settings.dictionary[0] = 'A';
settings.dictionary[1] = 'B';

logSettings(settings);