我已经开始在react应用程序中使用typescript,但我发现我在重复自己的操作,尤其是使用mapDispatchToProps
函数。
有没有更好的方法来声明类型?
我有一种感觉,我可能能够访问异步函数上使用的this
接口state
中的函数类型,但是,我对ts了解不够,在任何地方都找不到具体的答案。
索引.tsx
import { globalDispatchKeyData } from '../actions.tsx'
import { doSomething } from './services'
class Index extends Component {
// I declare it here
globalDispatchKeyData: (key: string, data: {}) => void
constructor(props: any) {
this.globalDispatchKeyData = this.props.globalDispatchKeyData.bind(this)
this.doSomething = doSomething.bind(this)
...
...
}
const mapDispatchToProps = { globalDispatchKeyData }
服务.tsx
interface IndexState {
// I also declare it here
globalDispatchKeyData: (key: string, data: {}) => void
}
export async function doSomething(this: IndexState) {
globalDispatchKeyData('TYPE', {})
}
这是当前为分派函数声明类型的唯一方法还是我遗漏了什么?
提前谢谢你的帮助!
最佳答案
可以为任何其他类型创建类型别名,以避免重复。
type DispatchKeyDataFn = (key: string, data: {}) => void
// Usage
globalDispatchKeyData: DispatchKeyDataFn
类型别名是非常灵活的,可以用来创建联盟、交叉点和许多其他文件。
https://www.typescriptlang.org/docs/handbook/advanced-types.html(下半部)