【发布时间】:2020-09-15 17:15:24
【问题描述】:
下面的代码给了我以下类型错误
没有重载匹配这个调用。 重载 1 of 3, '(callbackfn: (previousValue: TestData, currentValue: TestData, currentIndex: number, array: TestData[]) => TestData, initialValue: TestData): TestData',给出以下错误。 类型 'boolean' 不可分配给类型 'TestData'。 重载 2 of 3, '(callbackfn: (previousValue: BooleanObject, currentValue: TestData, currentIndex: number, array: TestData[]) => BooleanObject, initialValue: BooleanObject): BooleanObject',给出以下错误。 类型 'boolean' 不能分配给类型 'BooleanObject'。
有没有人能帮助解释为什么这个类型是不可分配的?
在我看来,在 TestState 接口中,我将属性“booleanObject”定义为 BooleanObject 类型,而 BooleanObject 是一个定义字符串索引属性的接口,这样当使用字符串索引时,返回值的类型应该是布尔值.
然后通过将reducer中的初始值强制转换为BooleanObject类型,
a) reducer 返回状态定义中属性“booleanObject”所期望的正确类型,并且
b) 然后当我索引累加器(类型为 BooleanObject)时,我相信我应该期待累加器 ["index"] 的值是布尔类型
我在哪里无法弄清楚为什么会出现 type not assignable 错误?
提前致谢!
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)
}
}
}
【问题讨论】:
标签: reactjs typescript