0

I want to build a type around the lines of :

interface Type<ofWhat>'fieldName'{
    fieldName: ofWhat[];
    otherProps: any;
}

Because the API endpoint has this weird design.

I've tried to do something like this:

type Page<T> = {pageInfo: PageInfo} | {[key:string]: Array<T>}

In which can subscribe to objects like :

    const obj2:Page<Card> = {
  pageInfo: {
    totalItens: 0,
    totalPages: 0,
    pageNumber: 0,
    lastPage: true
  },
  cards: [
    {
      header: "string",
      title: "string",
      content: "string",
      lawsuitId: "3fa85f64-5717-4562-b3fc-2c963f66afa6"
    },
  ]
}

However, this is problematic for the linter that doesn't understand that cards is a dynamic name and mark as an error.

Any ideas to improve this interface design? Thanks!

lrdass
  • 3
  • 3

1 Answers1

1

Using Record<> with a constrained type for the key seems to check out...

type BasePage = { pageInfo: PageInfo };
type Page<Key extends string, Type> = BasePage & Record<Key, Type[]>;

interface Card {
  header: string;
  title: string;
  content: string;
  lawsuitId: string;
}

interface PageInfo {
  totalItens: number;
  totalPages: number;
  pageNumber: number;
  lastPage: boolean;
}

type CardPage = Page<"cards", Card>;

const obj2: CardPage = {
  pageInfo: {
    totalItens: 0,
    totalPages: 0,
    pageNumber: 0,
    lastPage: true,
  },
  cards: [
    {
      header: "string",
      title: "string",
      content: "string",
      lawsuitId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    },
  ],
};

AKX
  • 152,115
  • 15
  • 115
  • 172