Fully Typesafe SDK

Fully Typesafe SDK

GrowthBook client-side SDKs have always been written in 100% Typescript, which provides a great baseline level of type safety. Trying to use a numeric feature flag value as a string? Get a compile-time error.

const value: string = gb.getFeatureValue("my-feature", 5.0);
// Error: Type 'number' is not assignable to type 'string'

This was done entirely through type inference. In the above example, we noticed you passed a number (5.0) as the fallback value, so we inferred the feature value was numeric. When you try to assign that to a string variable, Typescript complains.

However, there were two glaring holes in our approach:

  1. What if you made a typo in the feature name itself? (e.g. my-faeture )

  2. What if you used the wrong fallback value? (e.g. my-feature really is a string, the 5.0 is the real mistake)

With the latest release of our SDK, we are now able to catch both of the above during compile-time type checks:

// Argument of type '"my-faeture"' is not assignable to parameter...

gb.getFeatureValue("my-feature", 5.0);
// Argument of type 'number' is not assignable to parameter of type 'string'

How does it work?

The magic happens when creating the GrowthBook instance. You pass in an object describing all of your features and their data types. From that point forward, all of the methods on the GrowthBook instance will be strictly typed.

type AppFeatures = {
  "my-feature": string;
  "other-feature": boolean;

const gb = new GrowthBook<AppFeatures>(...);

The GrowthBook CLI

Creating AppFeatures manually and keeping it up-to-date can be tedious and error-prone. Luckily, we also released a handy command-line tool to generate these for you automatically.

First, install our CLI.

yarn add growthbook

Then, authenticate the CLI to your GrowthBook account using a Secret Access Key, which you can generate under Settings > API Keys.

yarn growthbook auth login --apiKey XXX

Lastly, add a script to your package.json to generate feature types and store them in a file:

  "scripts": {
    "type-gen": "growthbook features generate-types --output ./types"

Now you can run your script anytime features change within GrowthBook and it will generate a new TypeScript file that defines an AppFeatures type:

yarn type-gen

To use the generated types in your application, import them as follows:

import { AppFeatures } from "./types/app-features";

const gb = new GrowthBook<AppFeatures>(...);

What's Next?

We're just getting started with type safety. In the future, we want to support strongly typed targeting attributes and integration with all of our SDK languages - client-side, back-end, and mobile.

We also have a lot more planned for our GrowthBook CLI. Imagine being able to create and toggle features as part of a CI/CD pipeline. Or quickly spinning up a local webhook listener for development.