我有以下情况(代码片段,为简洁起见,省略了一些代码):
export class ValidationBuilderBase implements IValidationBuilder {
public isRequired(): IValidationBuilder {
const validationResult = Validators.required(this.baseControl);
if ((!isNullOrUndefined(validationResult) && !isNullOrUndefined(validationResult.required))) {
this.baseErrors['required'] = 'This input is required.'; // a ValdationErrors instance
}
return this;
}
}
export interface IValidationBuilder {
isRequired(): IValidationBuilder;
}
export class StringValidationBuilder implements IValidationBuilder {
constructor(private readonly builder: Validationbuilderbase) {}
isRequired(): StringValidationBuilder {
return this.builder.isRequired() as StringValidationBuilder;
}
}
// other code, this is in the function
let builder = new ValidationBuilder(this.formGroup.controls['test']);
let validator: StringValidationBuilder = new StringValidationBuilder(builder);
const result = validator.isRequired(); // what should this type be? StringValidationBuilder or IValidationBuilder?
我正在使用构建器模式执行一些代码,并返回其自身的实例的位置。但是,在开发人员工具中运行代码(通过业力茉莉花测试)时,validator.isRequired()
解析为类型IValidationBuilder
。
我期望它在StringValidationBuilder
实现接口时会导致StringValidationBuilder
,但是用StringValidationBuilder
覆盖返回类型,这应该是有效的吗?
我很困惑。在IDE(VsCode)中,代码完成指出返回类型应为StringValidationBuilder
编辑
我正在努力实现以下目标:
describe(`String validation chaining`, () => {
it(`should return no errors from the (valid) chain`, () => {
control().setValidators(Validators.required);
control().setValue('This is some test string......');
const result = validator
.string
.ifTrue((val) => false, 'error', 'should not reach here')
.ifFalse((val) => true, 'error', 'should not reach here')
.isRequired()
.maxLengthAllowed(100)
.minLengthAllowed(0)
.range(25, 35)
.build();
expect(result).toEqual(null);
});
});
我通过将代码修改为]使它正常工作>
export class StringValidationBuilder implements IValidationBuilder { isRequired(): StringValidationBuilder { this.builder.isRequired(); return this; } }
我仍然不相信这是理想的解决方案。
我有以下情况(代码片段,为简洁起见,省略了一些代码):导出类ValidationBuilderBase实现IValidationBuilder {public isRequired():IValidationBuilder {...
怎么可能是StringValidationBuilder
,您正在返回ValidationBuilderBase
,因为这就是生成器。而且StringValidationBuilder没有扩展它]