[英]array literal: This type can not be coerced to string
我有一個對象
const arr = [{ x: 1, y: 2 }];
我想在模板文字中使用它,因為我的用例但出現錯誤,假設我們使用模板文字記錄這個數組
console.log(`${arr}`);
我們會得到這個錯誤
array literal: This type can not be coerced to string
我如何在模板文字中使用數組的任何替代解決方案?
這是我的用例我有一個查詢
query {
processes(
page: 1,
itemsPerPage: 100,
filterBy: ${where}, // This is where I am getting this error, I want to pass an array here
) {
id
businessKey
name
processDefinition {
name
}
createDate
endDate
tasks {
id
}
}
}
但它被轉換為[Object Object]
。 我知道有限制,所以如果你能提出更好的解決方案嗎?
這是我的 where 對象
const where = [{ name: 'endDate', op: 'is null' }];
如果我理解正確,那么您要尋找的是:
filterBy: ${JSON.stringify(where)},
我用過這個功能
const formatArray = (array: Array<Object>) => {
if (!array || array.length === 0) {
return '[]';
}
const objs = array.map((obj) => {
return Object.entries(obj)
.map(([key, value]) => `${key}: "${String(value)}"`)
.join(', ');
});
return `[{${objs.join('},{')}}]`;
};
並將查詢更改為
query {
processes(
page: 1,
itemsPerPage: 100,
filterBy: ${formatArray(where)} // This is where I am formatting my array
) {
id
businessKey
name
processDefinition {
name
}
createDate
endDate
tasks {
id
}
}
}
它奏效了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.