How to type a custom pilet api?

187 views Asked by At

We are using the microfrontend framework piral. For our pilets we want to provide a custom api. Following the tutorials we came up with code like this

export interface MyApi {
  example(): void;
}

export function createMyApi(): Extend<MyApi> {
  return context => {
    return (api, target) => {
      return {
        example() {
          alert(`Hello from ${target.name}!`);
        }
      };
    };
  };
}

While this seems to be working functionally we could not get this to work with typescript. What are we doing wrong? How can we provide the typings in our pilets too?

1

There are 1 answers

0
Florian Rappl On BEST ANSWER

I think you may be missing the proper declaration merging.

import { PiletApi } 'piral-core';

declare module 'piral-core/lib/types/custom' {
  interface PiletCustomApi extends MyApi {}
}

So all in all:

import { PiletApi } 'piral-core';

export interface MyApi {
  example(): void;
}

declare module 'piral-core/lib/types/custom' {
  interface PiletCustomApi extends MyApi {}
}

export function createMyApi(): Extend<MyApi> {
  return context => {
    return (api, target) => {
      return {
        example() {
          alert(`Hello from ${target.name}!`);
        }
      };
    };
  };
}

Hope that helps!