如何使用 Typescript 为对象数组定义接口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25469244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:31:17  来源:igfitidea点击:

How can I define an interface for an array of objects with Typescript?

typescript

提问by basarat

I have the following interface and code. I thought I was doing the definitions correctly but I am getting an error:

我有以下界面和代码。我以为我的定义是正确的,但出现错误:

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:

错误:

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

采纳答案by Douglas

You can define an interface with an indexer:

您可以使用索引器定义接口:

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

回答by basarat

You don't needto use an indexer (since it a bit less typesafe). You have two options :

不需要使用索引器(因为它的类型安全性稍差)。你有两个选择:

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

interface EnumServiceItems extends Array<EnumServiceItem>{}


// Option A 
var result: EnumServiceItem[] = [
    { 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'] }
];

// Option B
var result: EnumServiceItems = [
    { 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'] }
]

Personally I recommend Option A (simpler migration when you are using classes not interfaces).

我个人推荐选项 A(当您使用类而不是接口时更简单的迁移)。

回答by NoNameProvided

You can define an interface as array with simply extending the Array interface.

您可以通过简单地扩展 Array 接口将接口定义为数组。

export interface MyInterface extends Array<MyType> { }

With this, any object which implements the MyInterfacewill need to implement all function calls of arrays and only will be able to store objects with the MyTypetype.

有了这个,任何实现 的对象MyInterface都需要实现数组的所有函数调用,并且只能存储具有该MyType类型的对象。

回答by Dane Brouwer

Additional easy option:

额外的简单选项:

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

    type simpleType = simpleInt[];

回答by Graham Mills

In Angular use 'extends' to define the interface for an 'Array' of objects.

在 Angular 中,使用“扩展”来定义对象“数组”的接口。

Using an indexer will give you an error as its not an Array interface so doesn't contain the properties and methods.

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

e.g

例如

error TS2339: Property 'find' does not exist on type 'ISelectOptions2'.

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

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

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

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

回答by roll

Also you can do this.

你也可以这样做。

            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'] }
            ];

回答by Euan Millar

Easy option with no tslint errors ...

没有 tslint 错误的简单选项......

export interface MyItem {
    id: number
    name: string
}

export type MyItemList = [MyItem]

回答by CiriousJoker

Here's an inline version if you don't want to create a whole new type:

如果你不想创建一个全新的类型,这里有一个内联版本:

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

回答by Rahmat Ali

Programming is simple. Use simple usecase:

编程很简单。使用简单的用例:

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

// use interface like
const result: IenumServiceGetOrderBy[] = 
                [
                    { id: 0, label: 'CId', key: 'contentId' },
                    { id: 1, label: 'Modified By', key: 'modifiedBy' },
                    { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] }
                ];


回答by Jeremy Levett

Do not use

不使用

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

You will get errors for all the Arrays properties and methods such as splice etc.

您将收到所有 Arrays 属性和方法(例如 splice 等)的错误。

The solution is to create an interface that defines an array of another interface (which will define the object)

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

For example:

例如:

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