gpt4 book ai didi

typescript - 实现可索引接口(interface)

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:07 24 4
gpt4 key购买 nike

我将如何实现可索引的接口(interface):

interface fooInterface{
// indexable
[index:string]:number;
[index:number]:number;
}


class Foo implements fooInterface{
// What goes here?
}

最佳答案

你永远不会在类定义中实现它,而只能通过寻址 instance[index],所以你的 fooInterface 不能通过 implements 使用 在 TypeScript 类上,但可用于描述对象的预期结构,例如var foo: fooInterface = {};

Describing an Indexable Object

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

关于typescript - 实现可索引接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com