typescript接口声明:indexable属性

时间:2014-03-28 00:09:49

标签: typescript

javascript对象的一个​​常见用例是将它们用作键值存储...有点像字典:

var dictionary = {},
    value;
dictionary['key a'] = 99;
dictionary['key b'] = 12;
value = dictionary['key a'];  // 99

typescript intellisense goodness可以通过声明这样的接口来添加:

interface IIndexable<T> {
    [s: string]: T;
}

并使用如下界面:

var dictionary: IIndexable<number> = {},
    value: number;
dictionary['key a'] = 99;
dictionary['key b'] = 'test';  // compiler error: "cannot convert string to number"
var x = dictionary['key a'];   // intellisense: "x" is treated like a number instead of "any".

这里是我的问题:是否可以声明此界面的独立版本:

interface StackOverflow {
    questions: IIndexable<number>;
}

即不使用IIndexable

我尝试过这样的事情,但它没有编译:

interface MyAttempt {
    questions: [s: string]: number;
}

1 个答案:

答案 0 :(得分:5)

interface MyAttempt {
    questions: { [s: string]: number; };
}