gpt4 book ai didi

javascript - JS流: How to initialize an empty object and set type as an argument to a function?

转载 作者:行者123 更新时间:2023-11-28 05:18:04 25 4
gpt4 key购买 nike

我有一个React reducer ,它设置一个事件用户,它是一个对象。我希望初始状态是一个空对象,{} 。但是,我无法弄清楚语法。这是我的尝试:

// @flow
import { SET_ACTIVE_USER } from '../actions/types';

type action = {
type: string,
payload: Object,
};

const state: Object = {};

export default (state: state, action: <action>) => {
switch(action.type) {
case SET_ACTIVE_USER:
return action.payload;
}

return state;
}

我也尝试过这样做: (state: Object = {}, action: <action>)但它也不起作用。

这是运行 flow 时的完整错误消息:

12: export default (state: state, action: <action>) => {
^ Unexpected token ,

另一种尝试是模仿像这样工作的参数:

// @flow
...

type state = {};

export default (state: <state>, action: <action>) : Object => {
...

我已阅读文档,但找不到正确的语法。

我在其他地方遇到了语法错误,修复它并将其转换为此似乎有效。不确定为什么会出现这种情况。

export default (state: Object = {}, action: action) : Object => {

所以,我想我的问题是,什么是正确的方法来做到这一点?

谢谢

最佳答案

在我看来,state 的类型是any。例如,Object 类型没有成员 a(在本例中这只是一个示例)。

/* @flow */

type state = {
[key: string] : any
};

type ACTION_TYPE = string;

interface action {
type: ACTION_TYPE,
payload: any
}

export default (action: action, state: state): state => {

return { a: '' };
};

<小时/>

edits type state = any could be even type state = {[key: string]: any} because is always true to assert that is an object with their keys of type string.

edits declaring state as Object: try to have a look at this playground

关于javascript - JS流: How to initialize an empty object and set type as an argument to a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40810510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com