【问题标题】:Is there a way to build a type interface with dynamic field name?有没有办法用动态字段名构建类型接口?
【发布时间】:2021-02-08 21:08:01
【问题描述】:

我想围绕以下行构建一个类型:

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

因为 API 端点有这种奇怪的设计。

我尝试过这样做:

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

其中可以订阅如下对象:

    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"
    },
  ]
}

但是,这对于不理解 cards 是动态名称并标记为错误的 linter 来说是有问题的。

有什么想法可以改进这个界面设计吗? 谢谢!

【问题讨论】:

标签: typescript typescript-generics react-typescript


【解决方案1】:

Record&lt;&gt; 与键 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",
    },
  ],
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2018-12-20
    • 2011-02-13
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多