【问题标题】:Axios GET returns a string which is an objectaxios GET 返回一个字符串,它是一个对象
【发布时间】:2022-01-18 23:34:13
【问题描述】:

我已经构建了一个发送axios 请求的函数。我使用typescript 并且不想使用any 作为函数的返回数据类型和axios 请求本身。

但是,问题是返回的对象包含参数 id,而参数 id 又是一个对象。 老实说,我从未见过这样的物体。我什至不知道那是什么东西。也许这是一些我从未听说过的基本东西。对此进行良好的谷歌搜索非常困难。

我想用它创建一个typescript interface。我什至没有一个好主意。

不胜感激

这是返回对象的一小部分:

 {
          data{
           '12345': { // params.id --> causing my poblem
                   address: {
             ...,
        }}}
    }
 

这是我的职责

async function getData (): Promise<IReturnData[]> {
const {data} = await axios.get<IReturnData>(`....${id}`) // in our case 12345
return Object.entries(data.data)[0];

}

我应该如何构建 IReturnData ?

    export interface IReturnData {
      data {
          string: { adress: Adress......
    }}}
   

    or 
    export interface IReturnData {
      data  {
          "1234 but that will change on every request": {
             adress: Adress......
     }}}
        

【问题讨论】:

    标签: javascript typescript http object axios


    【解决方案1】:

    我认为你能做的最好的就是使用Mapped Types。

    但这并不完美,请看下面的例子,或者this playground...

    interface MyModel {
        [key: string]: Address;
    }
    
    const goodExample: MyModel = {
        "12345": {
            country: "Germany"
        }
    }
    
    const badExample: MyModel = { // Sadly this also works, but I don't think there is a way to limit it to one key
        "12345": {
            country: "Germany"
        },
        "23456": {
            country: "Germany"
        }
    }
    

    【讨论】:

    • 嗨。谢谢。主要问题是,“1234”不是固定的。它随着请求的变化而变化
    • @maxfromgermany 在上面的类型中也不是固定的。 MyModel 将接受 "12345", "abc", ... 还是我没有正确理解您?
    猜你喜欢
    • 2018-04-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2017-09-22
    • 1970-01-01
    • 2023-04-05
    • 2019-09-24
    相关资源
    最近更新 更多