实现可索引的接口 [英] Implement an indexible interface
问题描述
我将如何实现可索引的接口:
How would I implement an interface that is indexible:
interface fooInterface{
// indexable
[index:string]:number;
[index:number]:number;
}
class Foo implements fooInterface{
// What goes here?
}
推荐答案
你永远不会在类定义中实现它,而只是通过寻址 instance[index]
,所以你的 fooInterface
不能通过 implements
在 TypeScript 类上使用,但可以用于描述对象的预期结构,例如var foo: fooInterface = {};
You don't ever implement it in the class definition, but only by addressing instance[index]
, so your fooInterface
cannot be be used via implements
on a TypeScript class, but can be used to describe the expected structure of an object, e,g. var foo: fooInterface = {};
描述可索引对象
JavaScript 中的一个常见模式是使用对象(例如 {})作为从一组字符串映射到一组值.当这些值是相同的类型,您可以使用接口来描述索引到一个对象总是产生某种类型的值(在这种情况下,小部件).
A common pattern in JavaScript is to use an object (e.g. {}) as way to map from a set of strings to a set of values. When those values are of the same type, you can use an interface to describe that indexing into an object always produces values of a certain type (in this case, Widget).
interface WidgetMap {
[name: string]: Widget;
}
var map: WidgetMap = {};
map['gear'] = new GearWidget();
var w = map['gear']; // w is inferred to type Widget
引用和小部件示例取自:http://blogs.msdn.com/b/typescript/archive/2013/01/24/interfaces-walkthrough.aspx
Quote and Widget example taken from: http://blogs.msdn.com/b/typescript/archive/2013/01/24/interfaces-walkthrough.aspx
这篇关于实现可索引的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!