typescript 对象类型中的条目数未知

polhcujo  于 2023-05-01  发布在  TypeScript
关注(0)|答案(2)|浏览(153)
export interface TitleBrickValues {
  title: EditableBrickField<string>;
  description: EditableBrickField<string>;
  links: EditableBrickField<EditableLink[]>;
}

export interface TeasersBrickValues {
  title: EditableBrickField<string>;
  contents: EditableBrickField<EditableLink[]>;
}

export interface DynamicTeasersValues {
  title: EditableBrickField<string>;
  description: EditableBrickField<string>;
  dynamicContents: EditableBrickField<EditableLink[]>;
}

和许多类似的类型。
基本上他们看起来都是

export interface DummyValues {
 
  randomKey: EditableBrickField<any>;
  // unknown number of keys that follow the same pattern
}

我尝试在父类型AnyBrick上的prop值下定义它,如下所示:

export interface AnyBrick {
  id: string;
  technicalName: TechnicalNames;
  patternId: string;
  layoutId: string;
  context: BrickContext;
  anchor: string;
  values: Record<string, EditableBrickField<any>>;
  outOfDate: MediasList[] | null;
  saveStatus: SaveStatus;
  status: number;
  isDiffNewBrick: boolean;
  wordsCount: number;
}

但是TypeScript抱怨道:

TS2430: Interface 'DynamicTeasersBrick' incorrectly extends interface 'AnyBrick'.   Types of property 'values' are incompatible.     Type 'DynamicTeasersValues' is not assignable to type '{ [key: string]: EditableBrickField<any>; }'.       Index signature for type 'string' is missing in type 'DynamicTeasersValues'.

如何解决AnyBrick的values属性类型?

camsedfj

camsedfj1#

错误消息告诉您DynamicTeasersValues类型不能分配给索引签名{ [key:String]:String;},因为它没有string类型的索引签名。要解决这个问题,您可以为DynamicTeasersValues和其他类似类型定义索引签名,如下所示:

export interface DynamicTeasersValues {
  title: EditableBrickField<string>;
  description: EditableBrickField<string>;
  dynamicContents: EditableBrickField<EditableLink[]>;
  [key: string]: EditableBrickField<any>;
}

这告诉TypeScript DynamicTeasersValues接口具有DummyValues的所有属性(即。即跟随模式串的随机数目的键:EditableBrickField),以及具有相同模式的任何其他属性。
您可以对其他接口执行相同的操作,如TitleBrickValues和TeasersBrickValues。然后,您可以更新AnyBrick接口以使用此新索引签名,如下所示:

export interface AnyBrick {
  id: string;
  technicalName: TechnicalNames;
  patternId: string;
  layoutId: string;
  context: BrickContext;
  anchor: string;
  values: {
    [key: string]: EditableBrickField<any>;
  };
  outOfDate: MediasList[] | null;
  saveStatus: SaveStatus;
  status: number;
  isDiffNewBrick: boolean;
  wordsCount: number;
}

这应该可以解决TypeScript错误,并允许您将AnyBrick接口用于遵循DummyValues模式的任何类型。
希望这有帮助!

2exbekwf

2exbekwf2#

在Adetoyese Kola-Balogun的帮助下,我找到了这个解决方案:

type BrickValues = {
  [key in 'title' | 'description' | 'dynamicContents' | 'links']?: EditableBrickField<string | EditableLink[]>;
};

export interface AnyBrick {
  id: string;
  technicalName: TechnicalNames;
  patternId: string;
  layoutId: string;
  context: BrickContext;
  anchor: string;
  values: BrickValues;
  outOfDate: MediasList[] | null;
  saveStatus: SaveStatus;
  status: number;
  isDiffNewBrick: boolean;
  wordsCount: number;
}

谢谢!

相关问题