小编Bri*_*hak的帖子

在TypeScript箭头函数中指定返回类型

我正在使用React和Redux并将操作类型指定为接口,以便我的Reducer可以利用标记的联合类型来提高类型安全性.

所以,我有类似的声明,如下所示:

interface AddTodoAction {
    type: "ADD_TODO",
    text: string
};

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

type TodoAction = AddTodoAction | DeleteTodoAction
Run Code Online (Sandbox Code Playgroud)

我想制作创建这些动作的辅助函数,我倾向于使用箭头函数.如果我写这个:

export const addTodo1 = (text: string) => ({
    type: "ADD_TODO",
    text
});
Run Code Online (Sandbox Code Playgroud)

编译器无法提供任何帮助以确保它是有效的,AddTodoAction因为未明确指定返回类型.我可以通过这样做明确指定返回类型:

export const addTodo2: (text: string) => AddTodoAction = (text: string) => ({
    type: "ADD_TODO",
    text
})
Run Code Online (Sandbox Code Playgroud)

但是这需要两次指定我的函数参数,所以它的冗长和难以阅读.

有没有办法在使用箭头符号时明确指定返回类型?

我想过尝试这个:

export const addTodo3 = (text: string) => <AddTodoAction>({
    type: "ADD_TODO",
    text
})
Run Code Online (Sandbox Code Playgroud)

在这种情况下,编译器现在推断返回类型,AddTodoAction但它不验证我返回的对象是否具有所有适当的字段.

我可以通过切换到不同的函数语法来解决这个问题:

export const addTodo4 = function(text: …
Run Code Online (Sandbox Code Playgroud)

typescript

85
推荐指数
3
解决办法
4万
查看次数

标签 统计

typescript ×1