英文:
typescript interface is not mapping to response
问题
我正在尝试将一个TypeScript接口映射到我的axios响应。在开发工具中,我在响应中看到了令牌
{"token":"f8ad0dc6-6092-4b26-be9b-a891aa856eef"}
但是当我尝试console.log(token)时,我得到undefined。
我已经尝试了两种方法。一种只使用JSON,另一种使用TypeScript接口。
完整的调用
async test() {
    try {
        await judgeApi.post<JudgeRequest>(`/submissions?${qs.stringify({
            language_id: 60,
            source_code: "cGFja2FnR29vZCBq...wbGUubmFtZSkKfQo=",
            stdin: "Sn...w"
        })}`).then(res => {
            return res.data.token
        })
    } catch (err) {
        console.log("error" + err);
    }
}
接口
interface JudgeRequest {
    token: string
}
测试
const token = await api.test()
console.log("token... " + token) <--- undefined.
然而,令牌在响应中!
英文:
I am trying to map a typescript interface to my axios response. In the dev tools I see the token in the response
{"token":"f8ad0dc6-6092-4b26-be9b-a891aa856eef"}
but I get a undefined when I try to console.log(token).
I have tried it two ways. One with just json and the other with a typescript interface.
await judgeApi.post<{token: string}>(`/submissions?${qs.stringify({
full call
async test() {
    try {
        await judgeApi.post<JudgeRequest>(`/submissions?${qs.stringify({
            language_id: 60,
            source_code: "cGFja2FnR29vZCBq...wbGUubmFtZSkKfQo=",
            stdin: "Sn...w"
        })}`).then(res => {
            return res.data.token
        })
    }catch (err) {
        console.log("error" + err);
    }
},
interface
interface JudgeRequest {
    token: string
}
testing
          const token = await api.test()
          console.log("token... " + token) <--- undefined.
However token is in the response!
答案1
得分: 1
这个问题发生在运行时,执行期间,与TypeScript无关。
在这里,你忘记在你的方法中返回Promise,所以你返回了一个Promise<void>。
async test() {
    // 返回 Promise
    return judgeApi.post<JudgeRequest>(`/submissions?${qs.stringify({
          language_id: 60,
          source_code: "cGFja2FnR29vZCBq...wbGUubmFtZSkKfQo=",
          stdin: "Sn...w"
    })}`)
    .then(res => {
         return res.data.token
    })
    .catch(err => {
        console.log("error" + err);
    })
},
英文:
Your problem is at runtime, during the execution, so this is not related with Typescript at all.
Here, you forgot to return the promise in your method, so you return a Promise<void>.
async test() {
    // return the promise
    return judgeApi.post<JudgeRequest>(`/submissions?${qs.stringify({
          language_id: 60,
          source_code: "cGFja2FnR29vZCBq...wbGUubmFtZSkKfQo=",
          stdin: "Sn...w"
    })}`)
    .then(res => {
         return res.data.token
    })
    .catch(err => {
        console.log("error" + err);
    })
},
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论