[英]Record<string, any> to {name: string} in typescript
I have a custom react hook to do a API calls:我有一个自定义反应挂钩来执行 API 调用:
const useFetch: (string) => Record<string, any> | null = (path: string) => {
const [data, setData] = useState<Record<string, any> | null>(null);
var requestOptions: RequestInit = {
method: "GET",
redirect: "follow",
};
const fetcher = async () => {
const res = await fetch(
process.env.REACT_APP_API_ENDPOINT + path,
requestOptions
);
const json = await res.json();
setData(json.data);
};
useEffect(() => {
fetcher();
}, [path]);
return data;
};
My problem is that I use this hook to call many different endpoints, so I cannot specify the type for data
in the hook.我的问题是我使用这个钩子来调用许多不同的端点,所以我不能在钩子中指定
data
的类型。 But when I call the hook, I know what the data is for that specific endpoint, so I want to specify a type for the variable storing the return value like:但是当我调用钩子时,我知道该特定端点的数据是什么,所以我想为存储返回值的变量指定一个类型,例如:
const data: { name: string } | null = useFetch('/example-end-point');
This is what I want to achieve, but I get this error: Property 'name' is missing in type 'Record<string, any>' but required in type '{ name: string; }'.
这是我想要实现的目标,但我收到此错误:
Property 'name' is missing in type 'Record<string, any>' but required in type '{ name: string; }'.
Property 'name' is missing in type 'Record<string, any>' but required in type '{ name: string; }'.
Using any
for the return type works, but I don't want to resort to that if there are any other ways to achieve this.使用
any
作为返回类型是可行的,但如果有任何其他方法可以实现这一点,我不想诉诸于此。
This is something that Generic Types can solve, you can absolutely allow for variable types to be passed into your single hook with a little bit of a code re-write.这是 Generic Types 可以解决的问题,您绝对可以允许将变量类型传递到您的单个钩子中,只需重新编写一点代码。
Take a look...看一看...
const useFetch: <T>(string) => Record<T> | null = (path: string) => {
const [data, setData] = useState<Record<T> | null>(null);
var requestOptions: RequestInit = {
method: "GET",
redirect: "follow",
};
const fetcher = async () => {
const res = await fetch(
process.env.REACT_APP_API_ENDPOINT + path,
requestOptions
);
const json = await res.json();
setData(json.data);
};
useEffect(() => {
fetcher();
}, [path]);
return data;
};
and then when you call it you can do the following.然后当你调用它时,你可以执行以下操作。
type MyData = {
name: string,
}
const data: MyData | null = useFetch<MyData>('/example-end-point');
You'd probably want to use unknown
instead of any
then narrow down the type elsewhere by performing some type guarding ie您可能希望使用
unknown
而不是any
然后通过执行一些类型保护来缩小其他地方的类型,即
const useFetch: (string) => unknown = (path: string) => {
...
const user = useFetch('/example-end-point')
if (!user || !user.name) throw new Error("Bad data")
const data: { name: string } = user
This way you get runtime data checking as well as type checking.通过这种方式,您可以获得运行时数据检查以及类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.