Skip to content

Type safety of Variant keys #967

Open
@cefn

Description

@cefn

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";
    },
  }),
});

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions