Home > Mobile >  Map enum values to a generic type
Map enum values to a generic type

Time:12-24

I am trying to use a generic to set a flexible value type for a given parameter. Parameter is an enum which defines what type of value can be used e.g. Parameter.DURATION should only accept a number however, there's clearly something wrong as it also accepts a string and I have no idea why. Perhaps there's a better way to map those types and enum values together.

Take a closer look at what setParameter() accepts when you hover over the call. It shouldn't accept string | number, it should accept number only.

function setParameter(parameter: Parameter, value: string | number): void

type ParameterType = string | number | boolean;

enum Parameter {
    ID = 'ID',
    TAG = 'TAG',
    DURATION = 'DURATION',
}

type ParameterNativeType = {
    [Parameter.ID]: string;
    [Parameter.TAG]: string;
    [Parameter.DURATION]: number;
}

function setParameter<T extends Parameter>(parameter: Parameter, value: ParameterNativeType[T]) {
  console.log(`Setting ${parameter} to ${value}`);
}

setParameter(Parameter.DURATION, '3');

Here's a link to TypeScript playground

Perhaps defining what the Parameter is might help but couldn't the function figure it out from the parameter argument somehow?

setParameter<Parameter.DURATION>(Parameter.DURATION, '3');

CodePudding user response:

That was tricky one! You're not using T for parameter type, that's why T is not inferred from provided argument and value type is not narrowed. Should be:

function setParameter<T extends Parameter>(parameter: T, value: ParameterNativeType[T]) {
  console.log(`Setting ${parameter} to ${value}`);
}

Playground

  • Related