如果你有一个 React 组件:
interface Chat {
someId: string;
}
export const Chat = (props: Chat) => {}
并且someId
设置在您的mapStateToProps
中:
function mapStateToProps(state: State) {
return {
someId: state.someId || ''
};
}
当我去使用此组件时<Chat />
我不需要指定someId
,因为它是由 redux 注入的。但是,打字稿抱怨is missing the following properties type 'Chat': 'someId'
一个令人讨厌的解决方法是将someId
设置为可选:
interface Chat {
someId?: string;
}
但这意味着您必须检查组件以某种方式存在于组件中。
正确的方法是什么?
您可以为 mapstate 和 mapdispatch 定义接口。并使用&
运算符获取组件道具类型。
interface StateProps {
someId: string;
}
interface DispatchProps {
someDispatch: () => void
}
type Props = StateProps & DispatchProps
const mapState = (state: State) => ({
someId: state.someId || ''
})
const mapDispatch = {
someDispatch: () => ({ type: 'SOME_ACTION_TYPE' })
}
const Chat = (props: Props) => {}
export default connect<StateProps, DispatchProps>(
mapState,
mapDispatch
)(Chat)