【问题标题】:"Base constructors must all have the same return type" when extending Angular 14 FormControl扩展Angular 14 FormControl时“基本构造函数必须具有相同的返回类型”
【发布时间】:2022-11-08 19:00:29
【问题描述】:
我正在尝试在 Angular 14 项目中扩展 FormControl 类,但我总是得到
“基本构造函数必须都具有相同的返回类型”
这是我的代码:
export class DWFormControl<T, K> extends FormControl<T> {
inputConfig?: K;
constructor(
value: FormControlState<T> | T,
opts: FormControlOptions & {
nonNullable: true;
},
inputConfig?: K
) {
super(value, opts);
this.inputConfig = inputConfig;
}
}
如果我把任何作为 FormControl 的泛型,这个错误就会消失,如下所示:
export class DWFormControl<T, K> extends FormControl<any> {
inputConfig?: K;
constructor(
value: FormControlState<T> | T,
opts: FormControlOptions & {
nonNullable: true;
},
inputConfig?: K
) {
super(value, opts);
this.inputConfig = inputConfig;
}
}
但我想使用键入表单的新功能,如果我使用它们,我将失去这些功能。
这个错误也可以在官方的 angular stackblitz here 中复制
【问题讨论】:
标签:
angular
angular-forms
【解决方案1】:
您可以使用与在 Angular 源代码中使用相同的模式。
https://github.com/angular/angular/blob/14.2.x/packages/forms/src/model/form_control.ts
export interface IEnhancedAbstractControlOptions {
// custom stuff
custom: boolean;
}
const defaultEnhancedAbstractControlOptions: IEnhancedAbstractControlOptions = {
custom: false,
};
export interface EnhancedFormControl<TValue = any> extends FormControl<TValue> {
custom: boolean;
}
type EnhancedFormControlInterface<TValue = any> = EnhancedFormControl<TValue>;
// Internal class, rip-off ɵFormControlCtor with enhanced typings
interface ɵEnhancedFormControlCtor {
new (): EnhancedFormControl<any>;
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions & { nonNullable: true }
): EnhancedFormControl<T>;
new <T = any>(
value: FormControlState<T> | T,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
_opts?: Partial<IEnhancedAbstractControlOptions>
): EnhancedFormControl<T | null>;
prototype: EnhancedFormControl<any>;
}
export const EnhancedFormControl: ɵEnhancedFormControlCtor = class EnhancedFormControl<
TValue = any
>
extends FormControl
implements EnhancedFormControlInterface<TValue>
{
custom: boolean;
constructor(
// formState and defaultValue will only be null if T is nullable
formState: FormControlState<TValue> | TValue = null as unknown as TValue,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
_opts?: Partial<IEnhancedAbstractControlOptions>
) {
super(formState, validatorOrOpts, asyncValidator);
const { custom } = { ...defaultEnhancedAbstractControlOptions, ..._opts };
this.custom = custom;
}
};