构造函数超负荷带有打字稿中有或没有破坏接口的构造函数,以允许位置或命名ARGS
我有一个具有一些必需属性和一些可选属性的类(我想在未设置时 undefined ,因为没有默认值)。有了可选的args,有很多参数,因此我希望能够清晰地命名它们,而如果没有可选的args,我想简洁地构造它。因此,我希望能够使用对象中的命名属性或作为位置参数构造它:
export interface ParamInterface {
a: number;
b: number;
c: number;
d?: number;
e?: number;
f?: number;
}
export class MyClass {
a: number;
b: number;
c: number;
d?: number;
e?: number;
f?: number;
constructor({a, b, c, d, e, f}: ParamInterface);
constructor(a: number, b: number, c: number, d?: number, e?: number, f?: number) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
}
换句话说,我希望能够致电:
new MyClass(1, 2, 3); // d, e, f will be undefined
new MyClass({a: 1, b: 2, c: 3}); // d, e, f will be undefined
new MyClass({a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}); // d, e, f will be set
然后我希望它提高错误:
new MyClass(1); // First three args required
但是,当我这样做时,我会发现此过载签名与其实现签名不兼容。
是否有任何方法可以使其兼容,或者其他方法可以实现我的目标后?
I have a class with some required attributes and some optional attributes (which I want to be undefined
when not set, as there's no default value). With optional args, there are a lot of parameters, so I would prefer to be able to name them for clarity, while without the optional args, I'd like to make it concise to construct. So, I want to be able to construct it using either named attributes in an object, or as positional arguments:
export interface ParamInterface {
a: number;
b: number;
c: number;
d?: number;
e?: number;
f?: number;
}
export class MyClass {
a: number;
b: number;
c: number;
d?: number;
e?: number;
f?: number;
constructor({a, b, c, d, e, f}: ParamInterface);
constructor(a: number, b: number, c: number, d?: number, e?: number, f?: number) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
}
In other words, I want to be able to call:
new MyClass(1, 2, 3); // d, e, f will be undefined
new MyClass({a: 1, b: 2, c: 3}); // d, e, f will be undefined
new MyClass({a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}); // d, e, f will be set
And then I want this to raise an error:
new MyClass(1); // First three args required
When I do this, though, I get an error that This overload signature is not compatible with its implementation signature.
Is there any way to make it compatible, or another way to achieve what I'm after?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的构造函数实现类型必须是所有声明的超级文档,如以下内容:
在这里我们有两个构造函数声明:
一个实现:
类型声明可以简化:
Your constructor implementation type must be supertype of all declarations, like following:
Here we have two constructor declarations:
and one implementation:
Type declaration can be a little simplified: