我已经开始在我的 React 应用程序中使用 TypeScript,但我发现我在重复自己,尤其是使用我的 mapDispatchToProps
函数。
有没有更好的方法来声明类型?
我有一种感觉,我也许能够访问异步函数中使用的 this
接口(interface) state
中的函数类型,但是,我没有对 TS 有足够的了解,但在任何地方都找不到具体的答案。
index.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 }
services.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 (向下半部分)
关于reactjs - 如何保持 TypeScript 类型干燥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448359/