如何为mapStateToProps指定正确的返回类型?

时间:2019-08-15 20:06:43

标签: typescript react-redux

在下面的mapStateToProps中,我想指定一个显式的TypeScript返回类型:

interface CounterProps {
    sequence: number;
    count: number;
}

class Counter extends Component<CounterProps> { 

    public static defaultProps = {
        sequence: 0,
        count: 0
    };

    public render() {
        const sequence = this.props.sequence
        const count = this.props.count

        return (
            // Some use of sequence, count ...
        )
    }
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const mapStateToProps = (state: CounterState) => ({
    count: state.count,
})
export default connect(mapStateToProps)(Counter)

然而using Partial的明显解决方案是

const mapStateToProps = (state: CounterState): Partial<CounterProps> => ({
        count: state.count,
    })

在调用connect时TS2345失败(Counter无法分配给期望的类型)。

或者,将未返回的成员设为可选

interface CounterProps {
    sequence?: number;
    count: number;
}

允许

const mapStateToProps = (state: CounterState): CounterProps => ({
    count: state.count,
})

可以正常工作,但会导致sequencerender的所有使用都为TS2352(可能未定义)。

如何为mapStateToProps指定正确的返回类型,根据规范,该类型仅需要返回相应类型的成员的子集?

1 个答案:

答案 0 :(得分:2)

尝试head(n = -1, do.call(rbind, lapply(split(dat, dat$ID), function(x) { rbind(x, c(x$ID[1], "F", "F")) }) ) ) ID type other.col 1.1 1 A1 cc 1.2 1 A2 dd 1.3 1 A3 cc 1.4 1 F F 2.4 2 A1 cc 2.5 2 B1 aa 2.3 2 F F 3.6 3 A2 aa Utility Type

由于您仅从Pick<T, K>返回具有单个属性“ count”的对象,因此应该可以将CounterProps用作Pick<CounterProps, 'count'>的返回类型

当您根据现有状态更改状态时,

mapStateToProps在通过回调调用Pick时也很有帮助。例如:

setState