I have some functions that I would like to reuse as methods across different React classes that are compatible. Is it possible in Typescript to pass the class to a function and have it correctly typed?
I want to do something like this...
// 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)
}
...
}
I had this working in JS, but moving to typescript, I am failing to get the proper type in the func args for the classes. I can see that it would have to be some kind of union type to allow for specific classes but IDK how to accomplish it. Any ideas?
Is there a better way to go about doing this?
const func = (cls: React.Component) => cls.setState({ key: "value" })? do you require specific fields on the state to be present in the class ? Then just specify them on the state generic parameter:const func = (cls: React.Component<any, {key: string}>) => cls.setState({ key: "value" })setState?const func = (cls: React.Component<any, {key: string}> & { method(): void }) => cls.method