type Templates = 'foo' | 'bar';
@Command('run')
class RunCommand implements CommandStruct {
@Option()
template: Template = 'foo';
public run() {}
}
In command registration above, when we execute command like bin run --template=baz
, Mustard doesnot validate if it's from pre-defined valid values, and we cannot add validation from @Validator.Enum()
.
But this can be a common suitation that we'd like to ensure valid user input for some options:
- If we received 'foo' or 'bar', use it;
- If we received
undefined
, use the default value;
- If we received any unexpected value, use the default value;
Decorator @Restrict
should help in such cases:
const templates = ['foo', 'bar'] as const;
type RestrictTemplates = typeof templates[number];
@Command('run')
class RunCommand implements CommandStruct {
@Option()
@Restrict(templates)
template: RestrictTemplates = 'foo';
public run() {}
}
Implementation:
function Restrict(restrictValues: Array<unknown> | Record<string, unknown>): ClassFieldDecorator {}
- When
restrictValues
was specified as array, we need to ensure the provided value was included by it.
- When
restrictValues
was an object(Enum usually), we need to ensure the provided value was included in all of its values;