Typescript 基于在基类中执行初始化的派生类的初始化对象类型
具有以下Typescript 基于在基类中执行初始化的派生类的初始化对象类型,typescript,typescript-typings,Typescript,Typescript Typings,具有以下基本字段类: export abstract class BaseField<T> { public abstract readonly controlType: ControlType; public key: string; public label: string; public order?: number; public value?: T; constructor(init?: Partial<Field<T>>
基本字段类:
export abstract class BaseField<T> {
public abstract readonly controlType: ControlType;
public key: string;
public label: string;
public order?: number;
public value?: T;
constructor(init?: Partial<Field<T>>) {
return Object.assign(this, init);
}
}
导出抽象类基字段{
公共摘要只读控件类型:controlType;
公钥:字符串;
公共标签:字符串;
公共秩序:编号;
公共价值:T;
构造函数(初始化?:部分){
返回Object.assign(this,init);
}
}
派生字段类:
export class TextBoxField<T> extends BaseField<T> {
public readonly controlType = ControlType.TextBox;
public minLength: number;
public maxLength: number
}
export class DropdownField<T> extends BaseField<T>{
public readonly controlType = ControlType.Dropdown;
public options?: Option<Date | string | number>;
}
export class NumberField<T> extends BaseField<T> {
public readonly controlType = ControlType.Number;
public min: number;
public max: number;
}
export type Field<T> =
| DropdownField<T>
| TextBoxField<T>
| NumberField<T>
export enum ControlType {
Dropdown,
TextBox,
Number,
}
导出类TextBoxField扩展了BaseField{
public readonly controlType=controlType.TextBox;
公共最小长度:数字;
公共最大长度:个
}
导出类DropdownField扩展了BaseField{
public readonly controlType=controlType.Dropdown;
公共期权:期权;
}
导出类NumberField扩展了BaseField{
public readonly controlType=controlType.Number;
公共min:编号;
公共最大值:个数;
}
导出类型字段=
|下降场
|TextBoxField
|数字域
导出枚举控制类型{
下拉列表,
文本框,
数字,
}
实例化派生字段时,与当前行为不同,当前行为的构造函数接受联合类型的初始化对象(由于BaseFeild
接受field
,后者是派生类的联合类型),我希望它接受基于派生类特定类型的相应初始化对象。(例如TextBoxField
不应接受属于NumberField
的min
属性)
有什么方法可以实现这种行为吗?谢谢。构造函数是执行您提到的约束时最烦人的地方之一。在其他情况下,我建议使用自动引用“当前”类或接口类型的类型。但是构造函数是静态成员,因此不能使用多态this
;有关支持它的功能请求,请参阅
静态方法有一个变通方法,允许您使用泛型来获得类似的行为,但这里不能这样做,因为构造函数不允许有this
参数:
class Sad {
// constructor(this: any) { }; // error!
// ---------> ~~~~~~~~~
// A constructor cannot have a 'this' parameter
}
class Mad {
constructor<T>() { }; // error!
// -------> ~
// Type parameters cannot appear on a constructor declaration
}
也不允许它们具有泛型类型参数:
class Sad {
// constructor(this: any) { }; // error!
// ---------> ~~~~~~~~~
// A constructor cannot have a 'this' parameter
}
class Mad {
constructor<T>() { }; // error!
// -------> ~
// Type parameters cannot appear on a constructor declaration
}
添加的名为This
的类型参数旨在由子类填充,如下所示:
class TextBoxField<T> extends BaseField<T, TextBoxField<T>> {
public readonly controlType = ControlType.TextBox;
public minLength: number = 0;
public maxLength: number = 1
}
class NumberField<T> extends BaseField<T, NumberField<T>> {
public readonly controlType = ControlType.Number;
public min: number = 0;
public max: number = 1;
}
好吧,希望这会有帮助;祝你好运
您能否将此代码设置为一个适合放入独立IDE中的代码,如?目前,存在未声明的类型和值以及一些--严格的模式错误,这些都是我在尝试提出解决方案之前需要克服的障碍。我添加了未声明的类型非常感谢您的详细解释!