我在我的项目中使用TypeScript,当我使用fetch调用API时,响应的类型是any。
const response = await fetch(url);
我知道这个响应的数据结构是一个对象
{id: string; code: string}
我可以使用下面的方法来分配响应的类型吗?如果没有,我可以知道这个要求的最佳实践吗?
const response: {id: string; code: string} = await fetch(url);
如果我只需要id,这样做可以吗?
const { id }: {id: string} = await fetch(url);
您应该创建类型化获取并在需要类型化响应时使用它:
async function typedFetch<T>(url: string): Promise<T> {
const response = await fetch(url);
const data = await response.json();
return data as T;
}
// Consumer
const response = await typedFetch<YourCustomType>('some/api/1'); // Here response will be of `YourCustomType` type