15. Generating TypeScript Types from oData Backend Structures

To avoid typos in field names and, in general, to make coding more convenient with clear and explicit autocompletion:

Pasted%20image%2020250715212637

... you can (and should!) import backend structure types directly into the frontend.

Moreover, you don't need to export or modify anything extra. All structure descriptions are already in the project in the localService folder.
Pasted%20image%2020250715212700

You just need to connect a library that will parse this XML and generate TypeScript types:

How to set up in an existing project:

  1. Install the library: npm install --save-dev @odata2ts/odata2ts

  2. Create a configuration:

    1. In the project root, create a file odata2ts.config.ts

    2. Fill it with the following content:

      import { ConfigFileOptions, Modes } from "@odata2ts/odata2ts";
      
      const config: ConfigFileOptions = {
        mode: Modes.models,
        skipEditableModels: false,
        skipIdModels: false,
        skipOperations: false,
        services: {
          odataService: {
            source: "webapp/localService/metadata.xml",
            output: "webapp/model/oDataModel",
          }
        }
      }
       
      export default config;
      
  3. In package.json, add to the scripts block:
    "gen-odata": "odata2ts"

  4. Now in the project directory you can run type generation/regeneration:
    npm run gen-odata

  5. In the model/oDataModel/ directory, you'll get structure definitions you can use in development
    Pasted%20image%2020250715212818

Usage:

import Controller from "sap/ui/core/mvc/Controller";
 
// Import the type you need, where Equipment is the EntityType name in oData
import {Equipment} from "project1/model/oDataModel/ZpmTorowebSrvModel";
 
/**
 * @namespace project1.controller
 */
export default class Main extends Controller {
 
    public onInit(): void {
 
        // Use as a regular TypeScript type
        const equipment : Equipment = { };
         
    }
}

Updating structures when the backend changes:

If backend structures change, the changes will NOT be applied automatically on the frontend. You need to do two things manually:

  1. In VSCode command → Fiori: Open Service Manager
    1. Go to edit the current oData service
    2. Refresh and save
  2. Run npm run gen-odata again

See also