简体   繁体   English

在通用接口中使用接口

[英]Using interfaces in generic interfaces

I use generics when using object literals to help simplify the process of interface building. 在使用对象文字帮助简化接口构建过程时,我会使用泛型。 So, for example, my base interface for all objects that use string as keys is 因此,例如,我使用字符串作为键的所有对象的基本接口是

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

If I wanted to use this to enforce an object to be entirely made of functions I'd make a new interface 如果我想使用它来强制对象完全由功能组成,我将创建一个新接口

interface IStringFunctionMap extends IStringTMap<Function> { };

Occasionally, however, I want to use more complex objects. 但是,有时我想使用更复杂的对象。 For example, let's say I wanted to build the following structure: 例如,假设我要构建以下结构:

var obj = {
    "group_1" : {
        "func_1" : function() {},
        "func_2" : function() {}
    },
    "group_2" : {
        "func_1" : function() {},
        "func_2" : function() {}
    }
}

I can build this interface pretty easily from raw bits 我可以从原始位很容易地构建此接口

interface IFunctionGroups { [s: string]: { [s: string]: Function } };

How would I go about making this more readable using my existing IStringTMap interface? 我将如何使用现有的IStringTMap接口使其更具可读性?

I've tried using my caveman logic, but just shoving one interface into another 我试过使用穴居人的逻辑,但只是将一个接口推到另一个

interface IFunctionGroups extends IStringTMap<IStringFunctionMap>;

Gives me the following error: 给我以下错误:

An interface an only extend an identifier/qualified-name with optional type arguments. 接口只能使用可选的类型参数扩展标识符/限定名称。

Adding curly braces { } after your interface declaration corrects the problem: 在接口声明后添加大括号{ }可解决问题:

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

interface IStringFunctionMap extends IStringTMap<Function> { }

interface IFunctionGroups extends IStringTMap<IStringFunctionMap> { }

var obj: IFunctionGroups = {
    "group_1" : {
        "func_1" : function() {},
        "func_2" : function() {}
    },
    "group_2" : {
        "func_1" : function() {},
        "func_2" : function() {}
    }
}

This compiles without errors or warnings to: 编译时不会出现错误或警告:

var obj = {
    "group_1": {
        "func_1": function () { },
        "func_2": function () { }
    },
    "group_2": {
        "func_1": function () { },
        "func_2": function () { }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM