Specify return type in TypeScript arrow function
There are 2 ways of achieving this with proper typing and minimal code:
interface AddTodoAction {
type: "ADD_TODO",
text: string
};
// Because the this keyword works different in arrow functions these
// 2 implementations are different in some cases:
// arrow function form/ function expression
const addTodo1 = (text: string): AddTodoAction => ({
type: "ADD_TODO",
text: text
})
// function declaration form
function addTodo2 (text: string): AddTodoAction {
return ({
type: "ADD_TODO",
text: text
})
}
Now the TS compiler can check the returned types. For example:
const todo = addTodo1('hi');
// Following gives TS compile time error
// addTodo1 returns AddTodoAction which does not have id on the type
const id = todo.id // Property 'id' does not exist on type 'AddTodoAction'.
First, consider the following notation from your original question:
export const addTodo3 = (text: string) => <AddTodoAction>({
type: "ADD_TODO",
text
})
Using this notation, you typecast the returned object to the type AddTodoAction
. However, the function's declared return type is still undefined (and the compiler will implicitly assume any
as return type).
Use the following notation instead:
export const addTodo3 = (text: string): AddTodoAction => ({
type: "ADD_TODO",
text: text
})
In this case, omitting a required property will yield the expected compiler error. For example, omitting the text
property will generate the following (desired) error:
Type '{ type: "ADD_TODO"; }' is not assignable to type 'TodoAction'.
Type '{ type: "ADD_TODO"; }' is not assignable to type 'DeleteTodoAction'.
Types of property 'type' are incompatible.
Type '"ADD_TODO"' is not assignable to type '"DELETE_TODO"'.
Also see the playground example.
I think your best bet is to create an interface for your function which has the right types, then you only need to specify that type, not all the nested types of your interface:
interface AddTodoAction {
type: "ADD_TODO",
text: string
};
interface AddTodoActionCreator {
(text: string): AddTodoAction;
};
export const addTodo: AddTodoActionCreator = (text) => ({
type: "ADD_TODO",
text
});
Update: How to do this with types
export interface GeneralAction<T> {
type: string;
payload: T;
}
export interface GeneralActionCreator<T> {
(payload: T): GeneralAction<T>;
}
export const SAVE_EVENT = 'SAVE_EVENT';
export const SaveEvent: GeneralActionCreator<UserEvent> = (payload) => {
return {type: SAVE_EVENT, payload};
};