Infer typings of Record

  Kiến thức lập trình

I’m currently using Typescript to strongly-type names and values for feature flags in our application. eg:

type FeatureFlagName = 'foo' | 'bar';

type FeatureFlags = Record<FeatureFlagName, boolean>;

const featureFlagDefaults: FeatureFlags = {
  'foo': false,
  'bar': false,
};

This has worked fine so far to ensure if you use featureFlagDefaults.foo, it expects it to be a boolean.

Now, I need to add a new feature flag, but its default value is a number. I can add it as follows:

type FeatureFlagName = 'foo' | 'bar' | 'another';

type FeatureFlags = Record<FeatureFlagName, boolean | number>;

const featureFlagDefaults: FeatureFlags = {
  'foo': false,
  'bar': false,
  'another': 10,
};

The problem, however, is that it doesn’t know if the value for any flag is boolean or number. I’m looking for a way to infer the type somehow. How can I do that so that when featureFlagDefaults.foo is referenced in code, it will see it as a boolean and when featureFlagDefaults.another is referenced in code, it will see it as a number?

3

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT