Typescript - 索引签名
warning:
这篇文章距离上次修改已过200天,其中的内容可能已经有所变动。
在TypeScript中,索引签名(index signatures)允许我们定义对象接口,这样就可以通过任意字符串作为属性名来访问对象的属性。
索引签名的语法是:
[index: string]: Type;
这里,index
是一个占位符,表示任意字符串可以用作索引,Type
是这些属性的类型。
下面是一个使用索引签名的例子:
interface StringDictionary {
[index: string]: string;
}
let myDictionary: StringDictionary = {
"hello": "Hello, world!",
"key2": "Some other value"
};
console.log(myDictionary["hello"]); // 输出: Hello, world!
console.log(myDictionary["key2"]); // 输出: Some other value
在这个例子中,StringDictionary
接口表示任意属性名的属性都是字符串类型。因此,myDictionary
可以有任意数量的属性,每个属性的值都是字符串。
评论已关闭