[英]Axios and Typescript : How assign a typed variable from Object
I'm currently working on a Next js App and i'm using Axios to call my external API.我目前正在开发 Next js 应用程序,我正在使用 Axios 来调用我的外部 API。
When i'm using Axios i can define a type to template the function like this:当我使用 Axios 时,我可以定义一个类型来模板 function,如下所示:
export type User = {
id: string
username: string
firstName: string
lastName: string
}
const response = await axios.get<User>(route, config)
But if the API send me more properties on data, the user is not a User anymore is just an object.但如果 API 向我发送更多关于数据的属性,则用户不再是用户,只是 object。
For example:例如:
Data received from the API从 API 收到的数据
{
id: "foo"
username: "foo"
firstName: "foo"
lastName: "foo"
email: "foo" // not in User
}
Then i will assign my user variable with the data然后我将用数据分配我的用户变量
const user: User = response.data // should be a User
Finally, if i log my user there is spare propeties like email最后,如果我登录我的用户,就会有像 email 这样的备用属性
console.log(user)
// give me
{
id: "foo"
username: "foo"
firstName: "foo"
lastName: "foo"
email: "foo"
}
// and not
{
id: "foo"
username: "foo"
firstName: "foo"
lastName: "foo"
}
So what is the interest of the template in the get function?那么get function中的模板有什么用呢?
and和
Is there a generic way to assign my typed variable with the object received and choose between fill my type with the value received and ignore spare propeties or fill my type with the value received and if there is one or more propeties in extra just return or throw an error?有没有一种通用的方法来分配我的类型变量与收到的 object 并选择用收到的值填充我的类型并忽略备用属性或用收到的值填充我的类型,如果有一个或多个额外的属性,只需返回或抛出一个错误?
Thanks谢谢
You can use type narrowing for this.您可以为此使用类型缩小。
const isUser = (candidate: any): candidate is User => {
return (
('id' in candidate && typeof candidate.id === 'string') &&
('username' in candidate && typeof candidate.username === 'string')
// etc
)
}
if (!isUser(dataFromApi)) {
throw new Error("Bad data structure")
}
After the isUser your code knows it is a User.在 isUser 之后,您的代码知道它是一个用户。 In practice I like to use superstruct for this.
在实践中,我喜欢为此使用上层结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.