Specify return type in TypeScript arrow function
<p>I am using React and Redux and have action types specified as interfaces, so that my reducers can take advantage of tagged union types for improved type safety.</p>

<p>So, I have type declarations that look like this:</p>

<pre><code>interface AddTodoAction {
    type: "ADD_TODO",
    text: string
};

interface DeleteTodoAction {
    type: "DELETE_TODO",
    id: number
}

type TodoAction = AddTodoAction | DeleteTodoAction
</code></pre>

<p>I'd like to make helper functions that create these actions, and I tend to use arrow functions for this. If I write this:</p>

<pre><code>export const addTodo1 = (text: string) =&gt; ({
    type: "ADD_TODO",
    text
});
</code></pre>

<p>The compiler can't provide any help in making sure this is a valid <code>AddTodoAction</code> because the return type isn't specified explicitly. I can specify the return type explicitly by doing this:</p>

<pre><code>export const addTodo2: (text: string) =&gt; AddTodoAction = (text: string) =&gt; ({
    type: "ADD_TODO",
    text
})
</code></pre>

<p>But this requires specifying my function arguments twice, so it's verbose and harder to read.</p>

<p>Is there a way I can specify the return type explicitly when using arrow notation?</p>

<p>I've thought of trying this:</p>

<pre><code>export const addTodo3 = (text: string) =&gt; &lt;AddTodoAction&gt;({
    type: "ADD_TODO",
    text
})
</code></pre>

<p>In this case, the compiler now infers the return type as <code>AddTodoAction</code> but it's doesn't validate that the object I'm returning has all of the appropriate fields.</p>

<p>I could solve this by switching to a different function syntax:</p>

<pre><code>export const addTodo4 = function(text: string): AddTodoAction {
    return {
        type: "ADD_TODO",
        text
    }
}

export function addTodo5(text: string): AddTodoAction {
    return {
        type: "ADD_TODO",
        text
    }
}
</code></pre>

<p>Either of these methods will cause the compiler to use the correct return type and enforce that I have set all fields appropriately, but they are also more verbose and they change the way '<code>this</code>' is handled in a function (which may not be an issue, I suppose.)</p>

<p>Is there any advice about the best way to do this?</p>