#Extending string literals in a declaration base in different packages

11 messages · Page 1 of 1 (latest)

azure scroll
#

Hi all, I'm trying to create an extendable types, which in turn lets the end user know that if they installed a package, they have access to that string literal, I setup a minimal example, anyone know how I can achieve this with literals?

When trying my example, I always end up with either "AlgoliaProduct" | "AlgoliaCategory" | "AlgoliaCms" or "MagentoProduct" | "MagentoCategory" | "MagentoCms" but never both of them together.

autumn tundraBOT
#
nemuksis#0

Preview:```ts
// @acme/types
export interface SitemapFetcherInterface {
compositions: string & {};
fetchers: string & {};
}

// @acme/package-foo
declare module "@acme/types" {
export interface SitemapFetcherInterface {
compositions: SitemapFetcherInterface["compositions"] | "products" | "category" | "cms";
...```

cloud halo
#

Have an interface dedicated for merging, and other packages merge into it like:

interface Composition {
    foo: true
    bar: true
}

Then the actual usage is just composition: keyof Composition.

azure scroll
#

I tried something like this as well, but results in the same thing, see updated example:

autumn tundraBOT
#
nemuksis#0

Preview:```ts
...
type CompositionKeys =
keyof SitemapFetcherInterface["compositions"]
type FetcherKeys =
keyof SitemapFetcherInterface["fetchers"]

// exported function to be consumed by end user
export function sitemapFetcher(
compositionName: CompositionKeys,
fetcherName: FetcherKeys
) {
// unrelated logic here
}
...```

cloud halo
#

That's not quite what I suggested

#

You'd have to merge top level, declaration merging doesn't allow you to merge inner properties.

#

So you need something like:

interface Composition {
    foo: true
    bar: true
}

interface Composition {
    baz: true
}
azure scroll
#

Ah I see I did this, it works now

// @acme/types
export interface SitemapCompositionList {}
export interface SitemapFetcherList {}


// @acme/package-a
declare module "@acme/types" {
  export interface SitemapCompositionList {
    products: "products";
    category: "category";
    cms: "cms";
  }
  export interface SitemapFetcherList {
    MagentoProduct: "MagentoProduct";
    MagentoCategory: "MagentoCategory";
    MagentoCms: "MagentoCms";
  }
}

// @acme/package-b
declare module "@acme/types" {
  export interface SitemapCompositionList {
    products: "products";
    category: "category";
    cms: "cms";
  }
  export interface SitemapFetcherList {
    AlgoliaProduct: "AlgoliaProduct";
    AlgoliaCategory: "AlgoliaCategory";
    AlgoliaCms: "AlgoliaCms";
  }
}
cloud halo
#

Yep you can use either the key or the value, and use the other one for metadata if you have any.

azure scroll
#

Thanks!