【问题标题】:typescript: reference current class typetypescript:引用当前类类型
【发布时间】:2018-11-03 23:34:27
【问题描述】:

是否可以在类型签名中引用当前类类型?这样我就可以做这样的事情:

 export class Component{
  constructor(config?: { [field in keyof self]: any }) {
      Object.assign(this, config)
  }
}

这个想法是传递一个由当前类键组成的配置对象。

我可以使用接口,但我需要输入相同部分的代码(在接口和实现类中)

另一种方法是使用泛型。像这样的:

export class Component<T>{
  init(config?: { [field in keyof T]?: any }) {
    Object.assign(this, config)
  }
}

class TestComponent extends Component<TestComponent>{
  foo: number
}
const component = new TestComponent().init({ foo: 11 })

但是拥有像class TestComponent extends Component&lt;TestComponent&gt; 这样的代码让我寻找更好的方法......

【问题讨论】:

  • 不可以写‘keyof Component’吗?还是我误解了你的问题?
  • 可以,但不能在构造函数中,可以使用this作为类型。 github.com/Microsoft/TypeScript/pull/4910
  • @TitianCernicova-Dragomir,哇,酷。这应该是一个答案。 this 不在构造函数中对我来说完全没问题。在 init 函数的某个地方做这样的事情更好,因为构造函数在默认值设置之前运行。
  • @SET 刚刚将其添加为答案 :)

标签: typescript


【解决方案1】:

你可以使用polymorphic this type引用当前类

export class Component{
  init(config?: { [field in keyof this]?: this[field] }) {
    Object.assign(this, config)
  }
}

class TestComponent extends Component{
  foo: number
}
const component = new TestComponent().init({ foo: 11 })
const component2 = new TestComponent().init({ foo: "11" }) // err

但是你不能在构造函数中使用this 作为类型

export class Component{
  constructor(config?: { [field in keyof this]?: this[field] }) { // error
    Object.assign(this, config)
  }
}

【讨论】:

  • 更糟糕的是,甚至不想在构造函数中做这种事情,因为类可能具有的默认值将在构造函数执行后填充,并且会覆盖来自配置对象的赋值.
【解决方案2】:

这不就行了吗?

export class Component {
  test = 123;

  constructor(config?: { [field in keyof Component]: any }) {
      Object.assign(this, config)
  }
}


new Component({ test: 123 }) // valid
new Component({ test1: 123 }) // invalid

Playground

甚至更短也会很简单(感谢鸭子打字)

constructor(config?: Component) {

也许没有真正表达你想说的/不够严格,但有效。

以下内容也是有效的

constructor(config = <Component>{}) {

直接给你一个空对象作为初始值。

来源:从 TypeScript v1 开始滥用这个。

【讨论】:

  • 在未来,我想要数百个不同的组件来扩展基本Component,所以我应该参考当前类,某种this,而不是基本Component
  • 它有什么变化? export class ChildComponent extends Component { constructor(config?: ChildComponent ) { super(config); }}
  • 它应该可以工作,但是这样一来,我每次都必须在每个继承的类中重新定义构造函数。接受的答案显示更好的解决方案。
  • 为什么需要重新定义构造函数?反正我看不出有什么问题。请发布不适用于此解决方案的内容
  • 它正在工作,但是如果您将有一些从 Component 继承的类,并且如果您需要将它们的属性分配给配置对象,那么您必须在每个此类中重新定义构造函数如您之前在 ChildComponent 类的示例中所示的类。
猜你喜欢
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 2011-11-13
  • 2017-07-09
  • 1970-01-01
  • 2018-01-16
相关资源
最近更新 更多