Reputation: 6373
Tryign to implement TypeScript with React/Redux and I'm running into some issues with my Types.
I have these types:
export interface IAuthState {
isSignedIn: Boolean | null;
userId: string | null;
}
export interface IStream {
id: string;
title: string;
description: string;
userId: string;
}
export interface IStreamState {
streams: { [index: string]: IStream };
}
Then I have two components:
interface IStreamsProps {
fetchStreams: () => void;
streams: IStreamState;
currentUserId: String | null;
isSignedIn: Boolean | null;
auth: IAuthState;
}
class StreamsList extends Component<IStreamsProps, IAppState> {
// Error: The Property Map does not exist on type IStreamState
renderList() {
return this.props.streams.map((stream: IStream) => (// CODE)
}
}
const mapStateToProps = (state: IAppState) => {
return {
streams: Object.values(state.streams),
currentUserId: state.auth.userId,
isSignedIn: state.auth.isSignedIn
};
};
export default connect(
mapStateToProps,
{ fetchStreams }
)(StreamsList);
Then I have another similar component:
const mapStateToProps = (state: IAppState, ownProps: HomeProps) => {
return {
//Error: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'IStreamState'
stream: state.streams[ownProps.match.params.id]
};
};
export default connect(
mapStateToProps,
null
)(StreamEdit);
How do I solve these two errors:
Error 1: The Property Map does not exist on type IStreamState
Error 2: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'IStreamState'
Upvotes: 0
Views: 260
Reputation: 7555
You incorrectly defined IStreamState
. Look closely. You've defined it as an object
export interface IStreamState {
streams: { [index: string]: IStream }[];
}
// equivalent declaration using type:
export type IStreamState = {
streams: { [index: string]: IStream }[]
}
I'm sure you mean to type it as just an array, as so:
export type IStreamState = { [index: string]: IStream }[]
EDIT:
While not directly related to your question, you need to be careful with your types. I noticed you used IAppState
in two different places. The class declarations are for props and local state. IAppState
appears to be for your redux store.
// the second generic argument is for `this.state`
class StreamsList extends Component<IStreamsProps, IAppState> {
EDIT2:
Defining both arguments in a class is optional. If you leave the second one out, it defaults to {}
for you.
It's impossible to be 100% sure as to why you're having that issue in your mapStateToProps
, because I don't know what IAppState
looks like. Just go double back and confirm your typing for state.streams
is exactly what you expect.
Upvotes: 2