cap-js / cds-types

Type definitions for CDS
Apache License 2.0
9 stars 8 forks source link

Use interface for cds_services to allow module augmentation #185

Open aschmidt93 opened 1 month ago

aschmidt93 commented 1 month ago

cds.services is currently typed as type cds_services: export type cds_services = { [name: string]: Service }. Types can not be extended via module augmentation, thus this does not work:

// index.d.ts
import "@sap/cds";

declare module "@sap/cds" {
  export declare type cds_services = { foo: "bar" };
}

cds.services would still be typed as { [name: string]: Service }.

In order for module augmentation to work, cds_services has to be an interface.

Idea

declare module "@sap/cds" {
  type service_dict = { [name: string]: Service }
  export interface cds_services extends service_dict {}
}

Now module augmentation can be used to extend cds_services:

// index.d.ts
import "@sap/cds";

declare module "@sap/cds" {
  export interface cds_services {
    foo: "bar";
  }
}

Now, cds.services.foo is properly typed as "bar".

Reason

This can be used to narrow down the type of cds_services to only those services that actually exist in the project. Additionally, cds-typer can be used to type those services.

daogrady commented 3 weeks ago

Hi Andreas,

thank you for your suggestion. I am actually not sure if module augmentation is the right approach here, as that is kind of a "last resort" technique and here it is used for added convenience. Wouldn't a helper type appropriately address the underlying issue?

Best, Daniel