我有以下界面和代码。我认为我做的定义是正确的,但我得到一个错误:
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'
您可以通过简单地扩展接口将类型定义为对象数组。
下面是一个例子:
// type of each item in the Service list
interface EnumServiceItem {
id: string;
label: string;
}
// type of the Service
interface ServiceType {
id: string,
label: string,
childList?: Array<EnumServiceItem>
}
// type of the Service list
type ServiceListType = Array<ServiceType>
let draggableList:ServiceListType = [
{
id: "1",
label: 'Parent Item 1',
childList: [
{
id: "11",
label: 'Child Item 1',
},
{
id: "12",
label: 'Child Item 2',
}
,
{
id: "13",
label: 'Child Item 3',
}
]
},
{
id: "2",
label: 'Parent Item 2',
childList: [
{
id: "14",
label: 'Child Item 4',
},
{
id: "15",
label: 'Child Item 5',
}
,
{
id: "16",
label: 'Child Item 6',
}
]
},
{
id: "3",
label: 'Parent Item 3',
childList: [
{
id: "17",
label: 'Child Item 7',
},
{
id: "18",
label: 'Child Item 8',
}
,
{
id: "19",
label: 'Child Item 9',
}
]
},
]
你也可以这样做。
interface IenumServiceGetOrderBy {
id: number;
label: string;
key: any;
}
// notice i am not using the []
var oneResult: IenumServiceGetOrderBy = { id: 0, label: 'CId', key: 'contentId'};
//notice i am using []
// it is read like "array of IenumServiceGetOrderBy"
var ArrayOfResult: IenumServiceGetOrderBy[] =
[
{ 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'] }
];