代码之家  ›  专栏  ›  技术社区  ›  Batman

响应redux typescript错误

  •  0
  • Batman  · 技术社区  · 5 年前

    尝试用react/redux实现typescript,我的类型遇到了一些问题。

    我有这些类型:

    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 };
    }
    

    然后我有两个部分:

    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);
    

    然后我有另一个类似的组件:

    
    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);
    

    如何解决这两个错误:

    错误1:IStreamState类型上不存在属性映射

    错误2:元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型“istreamState”

    1 回复  |  直到 5 年前
        1
  •  2
  •   Andrew    5 年前

    你的定义不正确 IStreamState . 仔细看。你把它定义为一个对象

    export interface IStreamState {
      streams: { [index: string]: IStream }[];
    }
    // equivalent declaration using type:
    export type IStreamState = { 
      streams: { [index: string]: IStream }[]
    }
    

    我敢肯定你的意思是把它作为一个数组来输入,所以:

    export type IStreamState = { [index: string]: IStream }[]
    

    编辑: 虽然与您的问题没有直接关系,但您需要小心处理您的类型。我注意到你用过 IAppState 在两个不同的地方。类声明用于props和 地方的 状态。 IAPP状态 似乎是你的Redux商店。

    // the second generic argument is for `this.state`
    class StreamsList extends Component<IStreamsProps, IAppState> {
    

    编辑2: {} 为你。

    你不可能百分之百地确定你为什么会有这个问题 mapStateToProps 因为我不知道 IAPP状态 看起来像。你只要回去确认一下 state.streams 正是你所期望的。