타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

안녕하세요! 오늘은 프로젝트 도중 Array 타입지정을 하는 방법을 알아보겠습니다! 🥷

우선 기본적으로 interface는 object를 다룹니다.

interface IFood {
	name: string;
	leftTime: string;
}

이런 식으로 말이죠!

그렇다면 이 인터페이스를 배열에 사용하고 싶으면 어떡해야할까요? 우리는 이 오브젝트를 가진 배열을 타입으로 지정해줘야 한다면 우리는 어떠한 행위를 해야할까요?! 🤔

그 것은 바로 IFood를 가지는 Array를 새로 만들어주어야 합니다! 한 번 코드로 확인해봅시다!

interface IFood {
	name: string;
	leftTime: string;
}

interface IFoods extends Array<IFood> {}

자 우린 IFood object를 갖는 IFoods라는 새로운 array interface를 만들었습니다. 이렇게 우리는 타입을 갖는 배열을 만들 수 있게 된거죠! 이제 IFoods를 통해 배열의 타입을 지정해줄 수 있습니다. 이런 식으로 말이죠! 🏃🏻‍♂️

export const foodState = atom<IFoods>({
	key: 'food',
	default: [
		{ name: '달걀', leftTime: '2022/04/21' },
		{ name: '우유', leftTime: '2022/05/19' },
	],
});

오늘도 새롭게 배열의 타입을 지정하는 법을 배웠습니다. 👏🏻 any로 해결할 수도 있겠지만, any를 여기저기 떡칠해버리면 타입스크립트를 굳이 이용하는 이유가 퇴색되어 버리죠 🥲

우리 귀찮아도 열심히 타입 지정해서, 후에 사이드이팩트를 최소화하고 유지보수 쉬운 코드를 만드는데 힘써보아요!

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

오늘도 읽어주셔서 감사합니다! 도움이 되었다면 좋겠습니다 😇

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'

Flip

5,8437 gold badges41 silver badges72 bronze badges

asked Aug 24, 2014 at 6:53

You don't need to 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).

answered Aug 24, 2014 at 10:33

basaratbasarat

247k54 gold badges441 silver badges497 bronze badges

7

You can define an interface with an indexer:

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

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

Dane Brouwer

2,6531 gold badge22 silver badges28 bronze badges

answered Aug 24, 2014 at 7:53

DouglasDouglas

35.9k8 gold badges73 silver badges89 bronze badges

6

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

export interface MyInterface extends Array<MyType> { }

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

answered Jan 17, 2017 at 7:00

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

NoNameProvidedNoNameProvided

8,3189 gold badges39 silver badges65 bronze badges

14

Additional easy option:

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

    type simpleType = simpleInt[];

answered Jun 18, 2019 at 9:27

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

Dane BrouwerDane Brouwer

2,6531 gold badge22 silver badges28 bronze badges

2

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.

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

answered May 19, 2020 at 9:24

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

Use like this!

interface Iinput {
  label: string
  placeholder: string
  register: any
  type?: string
  required: boolean
}


// This is how it can be done

const inputs: Array<Iinput> = [
  {
    label: "Title",
    placeholder: "Bought something",
    register: register,
    required: true,
  },
]

answered Sep 27, 2020 at 6:44

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

EricgitEricgit

5,1732 gold badges37 silver badges49 bronze badges

So I'll add my two cents :)

Let's say you want a Workplace type full of Persons. You need something like this:

Wrong! ... as interface


interface Workplace {
   name: string
   age: number
}[] 
// that [] doesn't work!! ;)

The problem here is that interface is for specifiing Class/Object shape .. not much more. So you may use type instead witch is much more flexible

Better -> use type instead of interface


type Workplace = {
   name: string
   age: number
}[] 

// This works :D

But maybe best is ...

define inner object Person with interface and then Workplace as type made by array of persons -> Person[]


interface Person {
   name: string
   age: number
}

type Workplace = Person[]

// nice ;)

Good luck

answered Jun 16 at 12:28

JsonKodyJsonKody

4423 silver badges13 bronze badges

0

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

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'.

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

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

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

answered Jul 19, 2019 at 10:52

2

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

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

answered Jun 26, 2018 at 17:35

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

CiriousJokerCiriousJoker

5041 gold badge7 silver badges18 bronze badges

1

Easy option with no tslint errors ...

export interface MyItem {
    id: number
    name: string
}

export type MyItemList = [MyItem]

answered Dec 6, 2017 at 12:22

Euan MillarEuan Millar

3361 gold badge5 silver badges13 bronze badges

3

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

answered Mar 13, 2019 at 0:18

RollyRolly

3,0033 gold badges23 silver badges32 bronze badges

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


answered Apr 22, 2020 at 15:48

타입스크립트 인터페이스 배열 - taibseukeulibteu inteopeiseu baeyeol

Rahmat AliRahmat Ali

1,3022 gold badges16 silver badges28 bronze badges

Here is one solution adapted to your example:

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

interface IenumServiceGetOrderBy extends Array<IenumServiceGetOrderByAttributes> {

}

let result: IenumServiceGetOrderBy;

With this solution you can use all properties and methods of the Array (like: length, push(), pop(), splice() ...)

answered Sep 10, 2020 at 12:39

AmelAmel

5355 silver badges13 bronze badges

I would use the following structure:

interface arrayOfObjects extends Array<{}> {}

And then it's easier to define:

let myArrayOfObjects: arrayOfObjects = [
  { 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"] },
];

answered Oct 7, 2021 at 16:52

You can define a type as an array of objects by simply extending the interface. Here's an example below :

// 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',
                }
            ]
        },

    ]

answered Apr 17 at 13:32