类型化reducer回调中的类型分配错误

时间:2020-05-28 11:44:53

标签: reactjs typescript

下面的代码给我以下类型错误

没有重载匹配此调用。 重载1之3,'((callbackfn:(previousValue:TestData,currentValue:TestData,currentIndex:number,数组:TestData [])=> TestData,initialValue:TestData):TestData',出现以下错误。 类型“布尔”不能分配给类型“ TestData”。 重载2之3,'((callbackfn:(previousValue:BooleanObject,currentValue:TestData,currentIndex:number,数组:TestData [])=> BooleanObject,initialValue:BooleanObject):BooleanObject',给出了以下错误。 不能将'boolean'类型分配给'BooleanObject'类型。

有人能帮助解释为什么类型不可分配吗?

在我看来,在TestState接口中,我将属性'booleanObject'定义为BooleanObject类型,而BooleanObject是一个接口,该接口定义了字符串索引属性,以便在使用字符串建立索引时,返回值的类型应为布尔值。

然后通过在化简器中转换初始值以键入BooleanObject,

a)约简器在状态定义中返回属性'booleanObject'所需的正确类型,并且

b)然后,当我索引累加器(类型为BooleanObject)时,我相信我应该期望accumulator [“ index”]值的类型为布尔值

我在哪里无法弄清楚为什么我遇到类型不可分配的错误?

谢谢!

import React from 'react';

interface TestProps {
    data: TestData[];
}

interface TestState {
    booleanObject: BooleanObject;
}

interface BooleanObject {
    [index: string]: boolean;
}

interface TestData {
    name: string;
    subData: SubData[];
}

interface SubData {
    name: string;
    value: string;
}

class Test extends React.Component<TestProps, TestState>{
    constructor(props: TestProps){
        super(props);
        this.state = {
            booleanObject: this.props.data.reduce((accumulator, currentValue) => accumulator[currentValue.name] = false, {} as BooleanObject)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

reduce函数的类型类似

Array<T>.reduce(callbackfn: (previousValue: T, currentValue: T, ..) => T): T

的意思是,它的结果是数组元素的类型。

因此,由于this.props.data的类型为TestData[],因此reduce方法必须返回类型为TestData的结果,这在您的代码中不是这种情况(强制转换并返回BooleanObject)。

答案 1 :(得分:0)

您的类型看起来还不错。

基本上,在您的reduce中,当您返回accumulator[currentValue.name] = false;时,这意味着您返回的是false(即布尔值),因此是问题所在。

只需正确地返回reduce回调,您的类型就会被修复。

import React from "react";

interface TestProps {
  data: TestData[];
}

interface TestState {
  booleanObject: BooleanObject;
}

interface BooleanObject {
  [index: string]: boolean;
  //   index: boolean;
}

interface TestData {
  name: string;
  subData: SubData[];
}

interface SubData {
  name: string;
  value: string;
}

class Test extends React.Component<TestProps, TestState> {
  constructor(props: TestProps) {
    super(props);
    this.state = {
      booleanObject: this.props.data.reduce((accumulator, currentValue) => {
        accumulator[currentValue.name] = false;
        return accumulator;
      }, {} as BooleanObject),
    };
  }
}