typescript - 类型“y”中缺少属性“x”,但在获取请求/返回期间类型“z”中需要属性“x”
问题描述
我有一个供异步函数使用的接口设置:
interface PostScriptTagResponse {
script_tag : {
readonly id : number
, src : string
, event : string
, readonly created_at : string
, readonly updated_at : string
, display_scope? : string
}
}
protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
try {
const data: PostScriptTagResponse = await fetch(fetchUrl, {
method: 'post'
, headers: {
"X-Shopify-Access-Token": this.generalToken
, "Content-Type": "application/json"
}
, body: {
script_tag : {
src: `${this.serverHost}/server/frontEndScriptControl.js`
, event: "onload"
, display_scope: "online_store"
}
}
}).json();
return data.script_tag;
// Property "script_tag" is missing in type {detailed interface spec here}
// but required in type "PostScriptTagResponse"
}
catch (e) {
// removed
}
}
我重新查看了上面的内容,认为格式是正确的,这是错误的吗?这是我希望从此获取请求中收到的示例响应:
https://help.shopify.com/en/api/reference/online-store/scripttag#create-2019-10
HTTP/1.1 201 Created
{
"script_tag": {
"id": 870402694,
"src": "https://djavaskripped.org/fancy.js",
"event": "onload",
"created_at": "2019-10-16T16:14:18-04:00",
"updated_at": "2019-10-16T16:14:18-04:00",
"display_scope": "all"
}
}
解决方案
问题在于这 3 行:
protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
const data: PostScriptTagResponse = await fetch(fetchUrl, {
return data.script_tag;
您正在等待data
,它来自 type PostScriptTagResponse
。然后你返回它的一个属性 ( script_tag
),它很可能不再来自 type PostScriptTagResponse
。但是你的函数签名说你想返回一个PostScriptTagResponse
.
因此,要么将函数签名更改为如下所示:
protected async createScriptTag(): Promise<YourScriptTagType|null> {
或者按原样返回响应并.script_tag
在消费者中使用该属性。
protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
return await fetch(fetchUrl, { //...
由于调用了您的函数,因此createScriptTag
您很可能希望执行第一种方法
推荐阅读
- c - 正则表达式意外模式匹配
- jquery - Jquery find(...).live 不是一个函数
- php - 致命错误:未捕获的错误:在 null 堆栈跟踪上调用成员函数 prepare():Database->query('SELECT jobs .*,...')Job->getAllJobs()
- r - 在 for 循环中使用“i”将函数应用于某些列
- dart - 是否可以初始化库?
- javascript - 如何使用momentjs检查当前时间是否在两次之间
- java - 处理库中的多个 Java 异常
- azure - 如何在 Azure (Powershell) 中使用带有 get-azlocation 的 sls
- c++ - C++20 中的严格别名规则是否允许标准 c++ unicode 字符和下划线类型之间的`reinterpret_cast`?
- javascript - 如何将带有索引元素的函数向下传递到组件?