Typescript + React:将类作为外部函数arg

时间:2018-07-15 02:34:51

标签: reactjs typescript

我有一些函数想作为兼容的不同React类之间的方法重用。在Typescript中是否可以将类传递给函数并正确键入?

我想做这样的事情...

// function to be reused across classes
const func = (class: [class type]) => this.setState({ key: "value" })

// class 1 that calls the function in a method
class Foo extends React.Component<{}, {}> {
  callFunc = () => {
    func(this)
  }
  ...
}

// class 2 that calls the function in a method
class Bar extends React.Component<{}, {}> {
  callFunc = () => {
    func(this)
  }
  ...
}

我在JS中工作,但是转到打字稿时,我无法在func参数的类中获得正确的类型。我可以看到它必须是某种联合类型才能允许特定的类,但IDK如何实现它。有什么想法吗?

是否有更好的方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

function参数需要指定需要由客户端类实现的协定。在这种情况下,参数应该是React.Component,该状态具有某些状态的字段,并且还可以具有函数将使用的某些方法。要获得额外的方法,我们可以使用交集类型(A & B)来指定参数为React.Component,并带有一些额外的方法。

// function to be reused across classes
const func = (cls: React.Component<any, { key: string, optionalKey?: string }> & { requiredMethod(): void; optionalMethod?(): void}) => {
  cls.setState({ key: "value" })
  cls.requiredMethod();
  if(cls.optionalMethod)cls.optionalMethod();
}

// class 1 that calls the function in a method
class Foo extends React.Component<{}, { key: string }> {
  callFunc = () => {
    func(this)
  }
  requiredMethod(){}
}

// class 2 that calls the function in a method
class Bar extends React.Component<{}, {key: string, optionalKey: string }> {
  callFunc = () => {
    func(this)
  }

  requiredMethod(){}
  optionalMethod(){}
}
相关问题