Is there a dynamic way to check values in typescript


I want to create

type ExtendedValueTypes = 'money' | 'land' | 'money_max' | 'land_max';
// dynamically from
type ValueTypes = 'money' | 'land';

I have a list of values

const values = ['money', 'land'] as const;
type ValueTypes = typeof values[number];
// equals ValueTypes = 'money' | 'land';

Now I want to dynamically extend my type to equal

type ExtendedValueTypes = 'money' | 'money_max' | 'land' | 'land_max';

I don’t want to have two separate arrays/types to maintain so I would like to have some type declaration that extends all strings in my type with ‘_max’.

const check = (type: ValueTypes) => 'some return'


// does not work but should


You can use template literal types to manipulate string literal types this way:

type ExtendedValueTypes = ValueTypes | `${ValueTypes}_max`
// type ExtendedValueTypes = ValueTypes | "money_max" | "land_max"

const check = (type: ExtendedValueTypes) => 'some return'



Playground link to code

Answered By – jcalz

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.