【问题标题】:Type for setting initial state on arrays用于设置数组初始状态的类型
【发布时间】:2021-07-07 16:04:46
【问题描述】:

我对 typeScript 有点陌生,任何人都可以识别 initialState 对象中 FilteredCars 数组的类型,代码来自 redux-toolkit 切片,我正在为项目使用 react

type  FilteredCarsProps = {
  id: string,
  name: string,
  address: string
}

interface initialStateProps {
  isFiltered: boolean,
  Filters : object,
  [FilteredCars: number]: FilteredCarsProps
}


export const initialState :initialStateProps={
  isFiltered: false,
  Filters : {},
  FilteredCars: [] //<====== This variable
}

【问题讨论】:

    标签: reactjs typescript interface redux-toolkit react-typescript


    【解决方案1】:

    在编写类型时,通常您复制粘贴对象的外观并将值更改为类型。在这种情况下:

    interface initialStateProps {
       isFiltered: true, // I change true to boolean
       Filters : {}, // this is an object
       FilteredCars: [] // this is an array, but array of what?
    }
    

    FilteredCars 属性应该是Array&lt;T&gt;,其中T 是这个数组,在本例中为FilteredCarsProps

    type FilteredCarsProps = {
      id: string,
      name: string,
      address: string
    }
    
    interface initialStateProps {
      isFiltered: boolean,
      Filters : object,
      FilteredCars: Array<FilteredCarsProps> <-- this should be fine
    }
    

    【讨论】:

    • 在编写类型时,通常您复制粘贴您的对象在这种情况下的样子 ``` interface initialStateProps { isFiltered: true, // 我将 true 更改为 boolean Filters : {}, //这是一个对象 FilteredCars: [] // 这是一个数组,但是数组是什么,Array 这里你的 T 是一个数组,在这种情况下 FilteredCarsProps } ``` - 抱歉,这里的注释格式不好-
    • 谢谢你,真的帮助我从 JS 到 TS 的旅程
    猜你喜欢
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2018-06-10
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    相关资源
    最近更新 更多