Home > Net >  Is there a dynamic way to check values in typescript
Is there a dynamic way to check values in typescript

Time:06-09

[TL:DR] 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'

//works
check('money');

// does not work but should
check('money_max')

CodePudding user response:

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'

//works
check('money');

//works
check('money_max');

Playground link to code

  • Related