【问题标题】:TypeScript Redux Action Create Function return typeTypeScript Redux Action 创建函数返回类型
【发布时间】:2021-01-03 00:48:30
【问题描述】:

使用 FSA 规则创建操作函数。

未指定返回类型,在eslint中显示警告。

我想在不修改eslint规则的情况下解决问题。

有没有一种简单的方法来指定除任何类型之外的类型?

github source code

const ADD_TODO = 'todos/ADD_TODO' as const;
const TOGGLE_TODO = 'todos/TOGGLE_TODO' as const;
const REMOVE_TODO = 'todos/REMOVE_TODO' as const;

// Missing return type on function!!!????
export const addTodo = (text: string) => ({
  type: ADD_TODO,
  payload: text,
});

// Missing return type on function!!!????
export const toggleTodo = (id: number) => ({
  type: TOGGLE_TODO,
  payload: id,
});

// Missing return type on function!!!????
export const removeTodo = (id: number) => ({
  type: REMOVE_TODO,
  payload: id,
});

type TodosAction = ReturnType<typeof addTodo> | ReturnType<typeof toggleTodo> | ReturnType<typeof removeTodo>;

export type Todo = {
  id: number;
  text: string;
  done: boolean;
};

export type TodosState = Todo[];

const initialState: TodosState = [
  { id: 1, text: 'Hi', done: true },
  { id: 2, text: 'Every', done: true },
  { id: 3, text: 'one', done: false },
];

function todos(state: TodosState = initialState, action: TodosAction): TodosState {
  switch (action.type) {
    case ADD_TODO: {
      const nextId = Math.max(...state.map((todo) => todo.id)) + 1;
      return state.concat({
        id: nextId,
        text: action.payload,
        done: false,
      });
    }
    case TOGGLE_TODO:
      return state.map((todo) => (todo.id === action.payload ? { ...todo, done: !todo.done } : todo));
    case REMOVE_TODO:
      return state.filter((todo) => todo.id !== action.payload);
    default:
      return state;
  }
}

export default todos;

【问题讨论】:

    标签: reactjs typescript redux react-redux redux-actions


    【解决方案1】:

    你能写一个泛型类型吗?是这样的:

    type ActionCreate<TP> = (p: TP) => { type: string, payload: TP };
    
    const addTodo: ActionCreate<string> = (v) => ({
      type: 'ADD',
      payload: v
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2017-11-02
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多