繁体   English   中英

接口上带有 Typescript 错误的 React-Redux 配置

[英]React-Redux Configuration with Typescript Error on Interface

我正在尝试学习如何使用 React-Redux 设置 Typescript,以便将来我使用 TS 做所有事情,只是为了学习。 我只想有一个动作来生成一个二维数字数组。 所以这就是我在做什么:

我的行动

import { GENERATE_PINS, AppActions } from '../types/actions';
import { generateAllPins } from '../utils/generatePins';
import { AppState } from '../configStore';
import { PinArr } from '../types/pinType';
import { Dispatch } from 'react';
// TypeScript infers that this function is returning SendMessageAction

export const getPin = (pins: PinArr): AppActions => ({
  type: GENERATE_PINS,
  pins
});

export const startGeneratePin = () => {
  return (dispatch: Dispatch<AppActions>, getState: () => AppState) => {
    const pins = generateAllPins();
    return dispatch(
      getPin({
        pins
      })
    );
  };
};

我的减速机

import { PinArr } from '../types/pinType';
import { GENERATE_PINS, PinActionTypes } from '../types/actions';

const initialState: PinArr = {
  pins: []
};

export function pinReducer(
  state = initialState,
  action: PinActionTypes
): PinArr {
  switch (action.type) {
    case GENERATE_PINS:
      return {
        pins: [...state.pins, ...action.pin]
      };
  }
}

我的类型

import { PinArr } from './pinType';

export const GENERATE_PINS = 'GENERATE_PINS';

interface GeneratePin {
  type: typeof GENERATE_PINS;
  pin: PinArr;
}

export type PinActionTypes = GeneratePin;

export type AppActions = PinActionTypes;

还有我的数据接口

export interface PinArr {
  pins: Array<Array<number>>;
}

我的引脚应该是 [[1,2,3,4], [2,3,4,5], [2,6,4,2]...] 所以这就是为什么我在做 Array>

现在我有两个错误:ON pin action

Type '{ type: "GENERATE_PINS"; pins: PinArr; }' is not assignable to type 'GeneratePin'.
  Object literal may only specify known properties, but 'pins' does not exist in type 'GeneratePin'. Did you mean to write 'pin'?

减速机上

Type 'PinArr' is not an array type.

任何人都可以帮助我吗? 我觉得一旦我理解并解决了这些接口类型(这就是我使用 TS 的原因,作为一个开发人员整体发展)我会觉得在 React 中使用 TS 会很舒服。 请?

由于您的命名约定(名称很重要),您已经把自己弄糊涂了! 您声明为PinsArray实际上PinReducer处理的状态切片。 如果你这样命名的话,我认为在你的代码中会更有意义:

type PinsArray = number[][]

interface PinState {
    pins: PinsArray
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM