Can't use @genType with Js.undefined<string> parameter

I’m trying to write some bindings for Firebase and getting stuck right at the beginning. I want to work with a function that initializes the Firebase app. It takes an optional name parameter that is - according to TypeScript - a string | undefined. But when I use Js.undefined<string> for that parameter, the generated TypeScript has an error - see below. I also tried to optional labeled arguments, but that doesn’t work since gentype turns those into an object, and the underlying function is just expecting the arguments flattened out in order. So I’m totally stuck. How do I use this function with optional arguments?

module AppConfig = {
  type t = {
    apiKey: string,
    authDomain: string,
    projectId: string,
    storageBucket: string,
    messagingSenderId: string,
    appId: string,
    measurementId: string,
  }
}

@genType.import("firebase/app") @genType.as("FirebaseApp")
type firebaseApp

@genType.import("firebase/app")
external _initializeApp: (. AppConfig.t, Js.undefined<string>) => firebaseApp = "initializeApp"

Error in generated .tsx file…

// Cannot find module './Js.gen' or its corresponding type declarations.
import type {undefined as Js_undefined} from './Js.gen';

Here is another failed attempt. The :

@genType.import("firebase/app")
external _initializeApp: (
  . AppConfig.t,
  @unwrap [#Name(string) | @as(Js.undefined) #Undefined],
) => firebaseApp = "initializeApp"

...and the code produced. Notice the variant is not unwrapped too.

export const initializeAppTypeChecked: (_1:AppConfig_t, _2:
    "Undefined"
  | { NAME: "Name"; VAL: string }) => firebaseApp = initializeAppNotChecked;

Wow kind of proud of myself! I think I solved this. Found 1 relevant Google hit around Js.gen. I think I needed a shim. I wish the error message could have pointed me in that direction. Didn’t know what Js.gen was. I added a src\shims folder and put a file in there called Js.shims.ts. This is what it contains…

export type undefined<T extends unknown> = T | undefined;

Updated my bsconfig.json to have…

  "gentypeconfig": {
    "language": "typescript",
    "shims": {"Js":"Js"},
    "generatedFileExtension": ".gen.tsx",
    "module": "es6",
    "debug": {
      "all": false,
      "basic": false
    }
  },

Now it seems to compile ok on the typescript side. When I changed the shim to a nonsense value like T | undefined | number I got an error.

Still wondering if there is a simpler way to deal with optional parameters and genType and if this is the best solution.

2 Likes