【发布时间】:2020-04-22 11:58:46
【问题描述】:
我有以下类层次结构
export abstract class AbstractControlModel<T> { ... }
export class FormArrayModel<T = any> extends AbstractControlModel<T[]> {
constructor(private readonly _controls: AbstractControlModel<T>[] = []) { ... }
findControl<E extends AbstractControlModel<T> = FormControlModel<T>>(index: number): E {
if (!(index in this._controls))
throw new Error(`Index "${index}" does not exist in this form array `);
return this._controls[index] as E;
}
}
export class FormGroupModel<T> extends AbstractControlModel<T>
constructor(private _controls?: { [E in keyof T]: AbstractControlModel<T[E]> }) { ... }
findControl<K extends keyof T>(name: K) {
return this.controls.get(name);
}
我创建了一个FormGroupModel 对象
const formGroup = new FormGroupModel({
fullName: new FormControlModel('Hello World'), // Inferred type is FormControlModel<string>,
addresses: new FormArrayModel([ // Inferred type is FormArrayModel<{street: string; city: string;}>
new FormGroupModel({ // Inferred type is FormGroupModel<{street: string; city: string}>
street: new FormControlModel('123 Street'),
city: new FormControlModel('City')
})
])
});
const fullNameControl = formGroup.findControl('fullName'); // The returned type is AbstractControlModel<any> instead of FormControlModel<string>
当我在上面的formGroup 变量上调用findControl 时,我希望TypeScript 返回一个FormControl<string> 类型的对象,而不是AbstractControl<any>。我应该如何更改声明以实现这一目标。非常感谢任何帮助。
【问题讨论】:
-
您能否将那些
...替换为可以编译并演示您的问题的内容?大概您需要FormGroup<T>来跟踪T的每个属性的控件类型,但是如果没有针对类层次结构的一些更具体的声明,我不确定如何最好地提出建议。除非您希望其他人编造一些东西,否则您不太可能对答案感到满意。祝你好运! -
好吧,我编造了一些东西!希望它能满足您的需求!
-
@jcalz 我为他们添加了完整的类定义
-
理想情况下,minimal reproducible example 的代码足以说明问题,最好是可以放入独立 IDE 中的代码,例如 The Playground。
-
@jcalz 添加了一个工作游乐场的链接
标签: typescript type-inference typescript-generics