如何在TypeScript中创建数组的预定义可接受值?

时间:2019-11-23 10:59:41

标签: typescript interface type-definition

我在TypeScript中有此对象:

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

我想在数组中定义某种可接受的值。像这样:

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

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

有没有办法在TypeScript中定义数组的可能值?

1 个答案:

答案 0 :(得分:1)

您快到了。只需将类型定义更改为

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