interface IUsers {
id: number;
name: string;
}
export const fetchUsers = () =>
fetch(`/users`).then((res) => res.json());
如何将 IUsers 类型添加到 fetchUsers 响应?fetchUsers 返回[{id:1, name:'fay'}].
interface IUsers {
id: number;
name: string;
}
export const fetchUsers = () =>
fetch(`/users`).then((res) => res.json());
如何将 IUsers 类型添加到 fetchUsers 响应?fetchUsers 返回[{id:1, name:'fay'}].
假设你已经写了这个:
export interface iUsers {
id : number
name : string
}
像这样修改你的方法:
export const fetchUsers = async () : Promise<{ data : iUsers[] }> => {
const response = await fetch(`/users`) ;
const data : iUsers[]= await response.json()
return { data }
}
并像这样使用它:
const { data } = await fetchUsers();
您可以将鼠标悬停在 IDE 上查看提示,它会显示这data
是一个iUsers[]
编辑 这是您想要的缩短版本,它可能不符合您的要求
export const fetchUsers = async () : Promise<iUsers[] > => await (await fetch(`/users`)).json() ;
并像这样使用它:
const data = await fetchUsers()