【发布时间】:2021-11-29 12:17:36
【问题描述】:
考虑一个自定义的useSignUp 钩子,其中mutate() 函数需要一些字段(在此示例中为name 和email):
export default function App() {
const name = "David";
const email = "david@gmail.com";
const signupMutation = useSignUp();
return (
<button
onClick={() => {
signupMutation.mutate(
{ name, email },
{
onSuccess: (result) => {
...
},
onError: (result) => {
// Wanted: result of type ErrorResult<"name" | "email">
}
}
);
}}
>
Sign Up
</button>
);
}
在这种情况下,我希望onError 的结果为ErrorResponse<"name" | "email"> 类型。但是,我得到了ErrorResponse<string>。
这是为什么呢?我如何指示 TypeScript 根据传递的数据推断特定类型(即"name" | "email",而不是string)?
这是我输入useSignUp的方式:
type SuccessResponse = {
userId: string;
};
type ErrorResponse<T> = {
userId?: string;
formErrors?: Array<{
field: T;
type: string;
}>;
};
export const useSignUp = <T extends string>() => {
return useMutation<SuccessResponse, ErrorResponse<T>, Record<T, string>>(
(data) => {
return new Promise((resolve, reject) => {
// Some logic here to either return a success or an error response
if (Math.random() > 0.5) {
resolve({
userId: "1234"
});
} else {
reject({
formErrors: [
{
field: "email", // I want TypeScript to complain if it's neither "name" nor "email"
type: "ALREADY_EXISTS"
}
]
});
}
});
}
);
};
【问题讨论】:
-
关于你的
reject签名,参数不能更改。请参阅this 答案。 -
@MishaMoroshko 你能提供可重现的例子吗?
标签: reactjs typescript react-hooks typescript-generics react-query