我有一个包含构造函数的类,该构造函数定义了类的属性。我需要使构造函数接受一个仅包含(扩展)类成员的对象。
abstract class A {
constructor(initializer: Partial<this>) { // <-- using this type in a constructor is not allowed!
for (const [key,value] of Object.entries(initializer)) {
Object.defineProperty(this, key, { value, enumerable: true })
}
}
static someStaticMethod() {}
someInstancemethod() {}
}
这个类仅用于被其他类扩展。
class B extends A {
a?: string
b?: number
c?: boolean
}
new B({ a: "hello", b: 1, c: true, d: "this must error" }) // <-- I want only properties of B here in the constructor argument
我知道可以给 A
添加类型参数,然后将扩展类分配给它
abstract class A<T> {
constructor(initializer: Partial<T>) {
...
}
}
class B extends A<B> {
...
}
但是,这种重复 B
的解决方案看起来不太优雅,尤其考虑到这是我正在开发的库的外部 API。有可能实现我想要的效果,并保留第一个示例中的语法 class B extends A
吗?如果不行,有什么可行的解决方案吗?
Playground 链接
B
作为通用参数重复使用是一种相当标准的模式,称为奇异递归模板模式。我同意这不是最优雅的解决方案,但它是相当标准的。 - Silvio Mayoloprivate
?Partial<B>
无法访问a
、b
或c
属性。当你写下“我知道我可以向A
添加一个类型参数,然后将扩展类分配给它”时,你尝试过了吗?在那里无法传递a
、b
或c
。你能否在你的问题中解决这个问题,使之只有一个障碍而不是多个? - jcalzthis
,但不能在构造函数本身中使用。如果这回答了你的问题,我可以写一篇文章并附上相关文档来解释它。如果不是,请问我漏掉了什么? - jcalz