Building a type-safe SDK with the Register pattern

Building a type-safe SDK with the Register pattern

The Typescript SDK for GrowthBook, our open source feature flagging and A/B testing platform, is about as generic as a library can get. You bring your own feature flags, your own targeting attributes, and your own event schema. The SDK has no idea what any of them are until runtime.

That's great for flexibility, but not so great for type safety.

const gb = new GrowthBook({ clientKey: "sdk-abc123" });

// Typo in the flag name
if (gb.isOn("new-chekout")) {
  ...
}

// This flag is actually a number
const color: string = gb.getFeatureValue("font-size", "blue");

Both of these compile just fine and because Javascript is so loosely typed they also don't throw obvious errors at runtime either. You end up with weird issues elsewhere in your code that take forever to debug.

Generics to the rescue?

The obvious solution is generics, and we've supported them for years.

interface AppFeatures {
  "new-checkout": boolean;
  "font-size": number;
}

const gb = new GrowthBook({ clientKey: "sdk-abc123" });

// Compile error!
gb.isOn("new-chekout");

Pretty straight forward. It does the job, but it's tedious and easy to forget.

import type { AppFeatures } from "../types/features";

// Needs to be passed every single time you use a hook
const showCheckout = useFeatureIsOn("new-checkout");

// If you forget, it falls back to loose typing - no compile errors
const showCheckout = useFeatureIsOn("checkout-new");

The usual workaround is to wrap every hook in your own pre-typed version. That's more boilerplate to maintain, and it only works as long as your agent doesn't decide to helpfully start using the original hook again.

The Register pattern

What we really want is to tell the SDK about our types once and have everything be typed from then on.

It turns out TypeScript can do this, and it starts with an empty interface in the SDK:

export interface Register {}

Interfaces in TypeScript have a strange property. If you declare the same one twice, the two declarations get merged together. And with declare module, you can do that to an interface that lives in someone else's package:

declare module "@growthbook/growthbook" {
  interface Register {
    features: AppFeatures;
  }
}

Now the SDK's Register interface has a features property, even though the SDK was published long before your AppFeatures type existed.

Back in the SDK, we can read it with a conditional type:

type RegisteredFeatures = Register extends { features: infer F }
  ? F
  : Record;

If you registered your features, use them. If not, fall back to the loose type we had before.

The last step is to use that as the default for our existing generics:

class GrowthBook<
  AppFeatures extends Record = RegisteredFeatures
> {
  ...
}

That's the whole thing. An empty interface, a conditional type, and a default. Now this works everywhere, with no generics and no imports:

const gb = new GrowthBook({ clientKey: "sdk-abc123" });

// Compile error!
gb.isOn("new-chekout");

// Compile error - expected 'number' not 'string'
const size = useFeatureValue("font-size", "12");

It's also fully backwards compatible. If you don't register anything, you get the same loose types as before. If you pass in a generic, that still wins.

This isn't a new idea. TanStack Router uses the same pattern (and the same Register name) for its route types, and styled-components does something similar with DefaultTheme. It's a great fit for any library where users bring their own schema.

More than feature flags

Once the plumbing is in place, it's really cheap to add more things to it. We now use the same interface for targeting attributes and tracked events:

declare module "@growthbook/growthbook" {
  interface Register {
    features: AppFeatures;
    attributes: AppAttributes;
    events: AppEvents;
  }
}

// Compile error! Unknown attribute "contry"
gb.setAttributes({ id: "123", contry: "US" });

// Compile error! "free" is not a valid plan
gb.logEvent("start_checkout", { plan: "free" });

Each one is optional. Anything you leave out stays loosely typed.

Skip writing the types too

There's still one manual step left - keeping the types up-to-date. Any time you add a new flag or attribute in GrowthBook, you now also need to update the type defs in your repo before you can use them.

To simplify this, we have a helpful method in our CLI that fetches the latest definitions from the GrowthBook API and outputs a Typescript file that registers the types.

npx growthbook generate-types --output ./src/generated

Run that on a schedule, in your CI/CD pipeline, or in a GrowthBook webhook listener and have it open a pull request whenever something changes.

A few gotchas

Inference takes precedence

TypeScript only uses a generic's default when it can't infer the type from the arguments. So this was silently accepted:

declare module "@growthbook/growthbook" {
  interface Register {
    attributes: { id: string }
  }
}

// AppAttributes is inferred as { idd: string }. No error!
const gb = new GrowthBook({
  attributes: { idd: "123" },
});

The fix is NoInfer, which tells TypeScript not to use an argument for inference. We had to add it anywhere a generic with a registered default shows up in a function's arguments:

class GrowthBookextends Attributes = RegisteredAttributes> {
  // Without NoInfer, the options you pass in decide what AppAttributes is
  constructor(options?: Options>) {
    ...
  }
}

Modules only

In Typescript, if you don't have at least one import or export statement in a file, then declare module statements will just silently not work. This is a pretty annoying quirk of Typescript and unfortunately the best we can do is warn people about it in our docs.

Register is global

There's one Register interface for your whole project. If you have two GrowthBook instances with different sets of flags, registering won't work for you. This is why we kept the generics around as a backup option.

How to get started

Type safety that you have to opt into at every call site isn't really type safety. The Register pattern let us flip that around. You opt in once, and from then on the low friction path is also the safe one.

All of this is available in version 2.1.0 of our JavaScript and React SDKs.

If you maintain a library where users bring their own schema, give the Register pattern a try yourself!

Happy typing!

Try a type-safe feature flag

Create a flag in GrowthBook and generate its TypeScript definition. Then misspell the flag key in your editor and watch TypeScript catch it.

Get Started for Free
Jeremy Dorn

Jeremy Dorn

Co-Founder & CTO, GrowthBook

Table of Contents

Related articles

See All Articles
No items found.

Ready to ship faster?

No credit card required. Start with feature flags, experimentation, and product analytics — free.

Simplified white illustration of a right angle ruler or carpenter's square tool.White checkmark symbol with a scattered pixelated effect around its edges on a transparent background.