我有以下界面和代码。我认为我做的定义是正确的,但我得到一个错误:

interface IenumServiceGetOrderBy { id: number; label: string; key: any }[];

and:

getOrderBy = (entity): IenumServiceGetOrderBy => {
        var result: IenumServiceGetOrderBy;
        switch (entity) {
            case "content":
                result =
                [
                    { id: 0, label: 'CId', key: 'contentId' },
                    { id: 1, label: 'Modified By', key: 'modifiedBy' },
                    { id: 2, label: 'Modified Date', key: 'modified' },
                    { id: 3, label: 'Status', key: 'contentStatusId' },
                    { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
                    { id: 5, label: 'Title', key: 'title' },
                    { id: 6, label: 'Type', key: 'contentTypeId' },
                    { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
                ];
                break;
        }
        return result;
    };

错误:

Error   190 Cannot convert '{}[]' to 'IenumServiceGetOrderBy':
    Type '{}[]' is missing property 'id' from type 'IenumServiceGetOrderBy'

当前回答

下面是一个适合你的例子的解决方案:

interface IenumServiceGetOrderByAttributes { 
  id: number; 
  label: string; 
  key: any 
}

interface IenumServiceGetOrderBy extends Array<IenumServiceGetOrderByAttributes> {

}

let result: IenumServiceGetOrderBy;

有了这个解决方案,你可以使用数组的所有属性和方法(比如: 长度,push(), pop(), splice()…

其他回答

下面是一个内联版本,如果你不想创建一个全新的类型:

export interface ISomeInterface extends Array<{
    [someindex: string]: number;
}> { };

在Angular中,使用“extends”来定义对象“Array”的接口。

使用索引器会给你一个错误,因为它不是数组接口,所以不包含属性和方法。

e.g

错误TS2339:属性“find”不存在类型“ISelectOptions2”。

// good    
export interface ISelectOptions1 extends Array<ISelectOption> {}

// bad
export interface ISelectOptions2 {
    [index: number]: ISelectOption;
}

interface ISelectOption {
    prop1: string;
    prop2?: boolean;
}

你可以用一个索引器定义一个接口:

interface EnumServiceGetOrderBy {
    [index: number]: { id: number; label: string; key: any };
}

简单的选项,没有tslint错误…

export interface MyItem {
    id: number
    name: string
}

export type MyItemList = [MyItem]

不要使用

interface EnumServiceGetOrderBy {
    [index: number]: { id: number; label: string; key: any };
}

你会得到错误的所有数组属性和方法,如splice等。

解决方案是创建一个接口,定义另一个接口的数组(该接口将定义对象)。

例如:

interface TopCategoriesProps {
  data: Array<Type>;
}
interface Type {
  category: string;
  percentage: number;
}