How to specify return type in TypeScript arrow function?
I am using React and Redux with action types defined as interfaces, which allows my reducers to take advantage of tagged union types for better type safety. I have the following type declarations:
interface AddTodoAction { type: “ADD_TODO”, text: string };
interface DeleteTodoAction { type: “DELETE_TODO”, id: number }
type TodoAction = AddTodoAction | DeleteTodoAction;
I want to create helper functions that generate these actions, and I prefer using arrow functions for this. For instance, I wrote the following:
export const addTodo1 = (text: string) => ({ type: “ADD_TODO”, text });
However, the compiler doesn’t provide any assistance in ensuring that this is a valid AddTodoAction
because the return type isn’t specified. I can explicitly specify the return type like this:
export const addTodo2: (text: string) => AddTodoAction = (text: string) => ({ type: “ADD_TODO”, text });
But this approach requires specifying the function arguments twice, which feels verbose and less readable.
I considered trying this:
export const addTodo3 = (text: string) => ({ type: “ADD_TODO”, text });
In this case, TypeScript infers the return type as AddTodoAction
, but it doesn’t validate that the returned object has all the correct fields.
I could solve this by switching to a different function syntax:
export const addTodo4 = function(text: string): AddTodoAction { return { type: “ADD_TODO”, text }; }
export function addTodo5(text: string): AddTodoAction {
return {
type: “ADD_TODO”,
text
};
}
These alternatives make the compiler use the correct return type and enforce that I include all required fields, but they are more verbose and also change the way this
is handled in the function (which might not be a problem).
Is there any advice or best practice for specifying the return type in typescript arrow function return type while keeping it concise and readable?