我有一个供异步函数使用的接口设置:
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
}
}我重新查看了上面的内容,我认为格式是正确的,这是错误的吗?下面是我希望从这个fetch请求中收到的一个示例响应:
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"
}
}发布于 2019-11-23 02:43:05
问题出在这3行代码中:
protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
const data: PostScriptTagResponse = await fetch(fetchUrl, {
return data.script_tag;您正在等待来自类型PostScriptTagResponse的data。然后返回它的一个属性(script_tag),这很可能不会再次来自类型PostScriptTagResponse。但是您的函数签名表明您希望返回一个PostScriptTagResponse。
因此,要么将函数签名更改为如下所示:
protected async createScriptTag(): Promise<YourScriptTagType|null> {或者按原样返回响应,并在使用者中使用.script_tag属性。
protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
return await fetch(fetchUrl, { //...由于您的函数名为createScriptTag,因此您很可能希望采用第一种方法
https://stackoverflow.com/questions/58999865
复制相似问题