Home > Mobile >  Is it possible to consume a typescript interface that does not fully match the data
Is it possible to consume a typescript interface that does not fully match the data

Time:10-20

I have an interface with fixed number of properties

export interface Page {
  title: string;
  description: string;
  heading: string | string[];
}

The data represented by that object comes from cms, however there are some dynamic properties that cms can return, these properties completely driven by cms so defining them as nullable (prop?: ...) within Page interface does not make any sense because there are too many props like that:

export interface Page {
  title: string;
  description: string;
  heading: string | string[];
  dynamicProp1?: string;
  dynamicProp2?: string;
}

So if I use that Page type the code-editor when accessing one of these one of that props. e.g:

const firstPage: Page = service.getPage('byId');
const dynamicPropX  = firstPage.dunamicPropX; //does not exist on interface but some exist in returned object.

I wonder if there any solution for that or should I just stick to any?

CodePudding user response:

Sounds like the use case for index signature:

Sometimes you don’t know all the names of a type’s properties ahead of time, but you do know the shape of the values.

export interface Page {
  title: string;
  description: string;
  heading: string | string[];
  [dynamicKeys: string]: string | string[] // Must be compatible with the fixed keys
}

declare const firstPage: Page;
const dynamicPropX  = firstPage.dunamicPropX; // Okay, but any key is now okay as well
//    ^? string | string[]

Playground Link

  • Related