如何声明字典的接口?

时间:2016-08-18 05:55:41

标签: typescript

我希望为我喜欢的插件添加定义,并希望知道如何在不使用任何类型的情况下定义类型以允许此类型。

我将使用这样的属性:

    views: {
        'list.view1': {
          dropPagingCap: 20,
          list_infiniteScroll: true,
          list_selectable: 'multi'
        },
        'list.view2': {
          dataSource: function(options, callback){ ... },
          dropPagingCap: 30,
          list_selectable: true
        }
    }

我试过这个,但是除了对象{}之外的库,而不是数组[]

interface IFuelUxRepeaterViews {
    [index: string]: IFuelUxRepeaterParametersBase | IFuelUxRepeaterListParameter | IFuelUxRepeaterTumbnailParameter | IFuelUxRepeaterAllParameter;
}

我不知道如何命名这种JavaScript类型的声明。

2 个答案:

答案 0 :(得分:7)

从您的代码示例中,您可以使用以下界面表示views

interface IFuelUxRepeaterViews {
    [index: string]: {
        dropPagingCap: number;
        dataSource?: (options: any, cb: () => void) => void;
        list_infiniteScroll?: boolean;
        list_selectable?: string | boolean;   
    }
}

答案 1 :(得分:0)

interface IFuelUxRepeaterParametersBase {
    dropPagingCap: number,
    list_selectable: boolean | string
}

interface IFuelUxRepeaterTumbnailParameter extends IFuelUxRepeaterParametersBase {
    list_infiniteScroll: boolean,
}

interface IFuelUxRepeaterListParameter extends IFuelUxRepeaterParametersBase {
    dataSource: (x: any, y: any) => any,
}

interface IFuelUxRepeaterViews {
    [index: string]: IFuelUxRepeaterParametersBase | IFuelUxRepeaterListParameter | IFuelUxRepeaterTumbnailParameter ;
}


let views: IFuelUxRepeaterViews = {
    'list.view1': {
        dropPagingCap: 20,
        list_infiniteScroll: true,
        list_selectable: 'multi'
    },
    'list.view2': {
        dataSource: (options, callback) => { },
        dropPagingCap: 30,
        list_selectable: true
    }
}