typescriptinterfacetype-definition

How to create predefined acceptable values of array in TypeScript?


I have this object in TypeScript:

validationRules: ValidationRuleInterface = {
  id: ['integer', 'required'],
  name: ['string', 'required', 'people_name'],
  city: ['string', 'nullable'],
};

I want to define somehow acceptable values in arrays. Something like this:

type Rule = string<'required' | 'nullable' | 'string' | 'integer' | 'people_name', null>;

interface ValidationRuleInterface {
  [key: string]: Rule[]
}

Is there any way to define possible values of an array in TypeScript?


Solution

  • You were almost there. Simply, change the type definition to

    type Rule = 'required' | 'nullable' | 'string' | 'integer' | 'people_name' | null;