繁体   English   中英

数组字面量:此类型不能强制为字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM