打字稿:参考当前班级类型

时间:2018-11-03 15:01:56

标签: typescript

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

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

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

我可以使用接口,但随后我需要在接口和实现类中键入twise的相同部分

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

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<TestComponent>之类的代码使我可以寻找更好的方法...

2 个答案:

答案 0 :(得分:2)

您可以使用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)
  }
}

答案 1 :(得分:-1)

这不行吗?

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起滥用此内容。