Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

reactjs - TypeScript Redux Action Create Function return type

create action function with FSA rules.

The return type is not specified, warning is displayed in the eslint.

I want to solve the problem without revising the rules of eslint.

Is there an easy way to designate a type except for any type?

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;
question from:https://stackoverflow.com/questions/65545645/typescript-redux-action-create-function-return-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Could you write a generic type? Somthing like this:

type ActionCreate<TP> = (p: TP) => { type: string, payload: TP };

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...