【发布时间】:2017-03-09 07:10:12
【问题描述】:
我正在使用 React 和 Redux 并将操作类型指定为接口,以便我的 reducer 可以利用标记的联合类型来提高类型安全性。
所以,我的类型声明如下所示:
interface AddTodoAction {
type: "ADD_TODO",
text: string
};
interface DeleteTodoAction {
type: "DELETE_TODO",
id: number
}
type TodoAction = AddTodoAction | DeleteTodoAction
我想制作创建这些动作的辅助函数,并且我倾向于为此使用箭头函数。如果我写这个:
export const addTodo1 = (text: string) => ({
type: "ADD_TODO",
text
});
编译器无法提供任何帮助来确保这是一个有效的AddTodoAction,因为没有明确指定返回类型。我可以通过这样做明确指定返回类型:
export const addTodo2: (text: string) => AddTodoAction = (text: string) => ({
type: "ADD_TODO",
text
})
但这需要指定我的函数参数两次,所以它很冗长且难以阅读。
有没有一种方法可以在使用箭头符号时明确指定返回类型?
我想过试试这个:
export const addTodo3 = (text: string) => <AddTodoAction>({
type: "ADD_TODO",
text
})
在这种情况下,编译器现在将返回类型推断为 AddTodoAction,但它不会验证我返回的对象是否具有所有适当的字段。
我可以通过切换到不同的函数语法来解决这个问题:
export const addTodo4 = function(text: string): AddTodoAction {
return {
type: "ADD_TODO",
text
}
}
export function addTodo5(text: string): AddTodoAction {
return {
type: "ADD_TODO",
text
}
}
这两种方法中的任何一种都会导致编译器使用正确的返回类型并强制我已正确设置所有字段,但它们也更加冗长,并且它们改变了在函数中处理“this”的方式(其中我想可能不是问题。)
对于最好的方法有什么建议吗?
【问题讨论】:
-
getTitle = ():string => 'State Lists'
标签: typescript