js-sdk icon indicating copy to clipboard operation
js-sdk copied to clipboard

Type safety of Variant keys

Open cefn opened this issue 1 year ago • 4 comments

Requirements

I was just examining the API to look at adopting a feature-flagging standard and surprised to find that after defining a strict set of variants, there is no Typescript compiler error when providing a defaultVariant which is not in the list of variants. Similarly it is not a compiler error to return a random value for the variant from contextEvaluator.

Can these be made type-safe, please? There should be two compiler errors in the code below, and there are none. See playground

import { InMemoryProvider } from '@openfeature/react-sdk';

const provider = new InMemoryProvider({
    something: {
        disabled: false,
        variants: {
            hey: true,
            yo: false,
        },
        defaultVariant: 'not_a_variant',
        contextEvaluator: (context) => {
            return 'also_not_a_variant'
        }
    }
})

A workaround for type safety is to use a helper function like createVariant below, but to make the most of this, then InMemoryProvider should be defined as generic, to allow the const features of the configuration object passed to it to drive other parts of the API it exposes - e.g. flag names and variants are typed correspondingly when retrieved...

import { InMemoryProvider, EvaluationContext } from "@openfeature/react-sdk";

function createVariant<const T extends Partial<Record<string, unknown>>>(o: {
  variants: T;
  defaultVariant: keyof T;
  contextEvaluator: (context: EvaluationContext) => keyof T;
  disabled: boolean;
}) {
  return o;
}

const provider = new InMemoryProvider({
  something: createVariant({
    disabled: false,
    variants: {
      hey: true,
      yo: false,
    },
    defaultVariant: "not_a_variant",
    contextEvaluator: (context) => {
      return "also_not_a_variant";
    },
  }),
});

cefn avatar Jun 21 '24 13:06 cefn

Hey @cefn, the InMemoryProvider was mainly built for demo and testing purposes. However, I can see the value of adding an additional type safety. I'll mark this as a Good First Issue.

beeme1mr avatar Jun 21 '24 14:06 beeme1mr

Im looking to contribute to this project, and will try and take a stab at this "good first issue" !

wichopy avatar Sep 28 '24 20:09 wichopy

@wichopy if you are still interested in this I can assign you.

toddbaert avatar Oct 18 '24 16:10 toddbaert

sure assign me

wichopy avatar Oct 18 '24 19:10 wichopy