Typescript Interface Generation | Yext Hitchhikers Platform

Overview

book
Note
You must be on Yext CLI version 0.1_342 or higher to use this command. Refer to our installation guide for more information.

TypeScript makes useful patterns from typed object-oriented programming available to JavaScript developers.

For Pages development, the Yext CLI offers a command that automatically generates interfaces for your project based on Stream objects in your templates .

To utilize this feature, run the following command from the root of your project:

yext types generate pages
book
Note
You need to run npm run dev before you can generate types and after you make edits to the TemplateConfig of any of your templates. This is because the Yext CLI looks at JSON files in the dist folder to generate types which are created/refreshed each time you restart the development server.

Once you have run the command, a file containing your generated interfaces will be automatically written to src/types/autogen.ts. From there, you can easily import these interfaces into your components.

Using Generated Types in Your Templates

Given the following TemplateConfig:

// src/templates/locations.tsx

export const config: TemplateConfig = {
  stream: {
    $id: "locations",
    fields: ["id", "name", "slug", "address"],
    filter: {
      entityTypes: ["location"],
    },
    localization: {
      locales: ["en"],
    },
  },
};

The following type will be generated after running yext types generate pages:

// src/types/autogen.ts

export interface Locations {
  id: string,
  name: string,
  slug: string,
  address: Address,
}

When using the generated Locations type, type your template function as Template<TemplateRenderProps<Locations>> to ensure it receives the correct structure of props, including the document object shaped as Locations:

// src/templates/locations.tsx

const LocationsTemplate: Template<TemplateRenderProps<Locations>> = ({ document }) => {
  const { id, name, address } = document;

  return (
    <>
      {/* render Location fields here */}
    </>
  );
};

Limitations

This command only supports one level of nesting for entity references. Refer to the example stream definition below:

export const config: TemplateConfig = {
  stream: {
    $id: "Example Stream",
    filter: {...},
    fields: [
      "c_entityList.field1",
      "c_entityList.field2",
      "c_entityList.c_entityList2.field1",
      "c_entityList.c_entityList2.field2"
    ],
    localization: {...},
  },
};

The code snippet below shows the resulting interfaces (note, c_entityList2 is omitted from the interface, due to the fact that it exceeds one level of nested depth):

export interface ExampleStream {
  c_entityList: C_relatedMenuItems[],
}

export interface C_entityList {
  field1?: string,
  field2?: string,
}
Feedback