Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map enum values to a generic type

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading