简体   繁体   English

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

[英]array literal: This type can not be coerced to string

I have an object我有一个对象

const arr = [{ x: 1, y: 2 }];

I want to use it in template literals, because of my use case but getting error, Suppose if we log this array using template literal like我想在模板文字中使用它,因为我的用例但出现错误,假设我们使用模板文字记录这个数组

console.log(`${arr}`);

We will get this error我们会得到这个错误

array literal: This type can not be coerced to string

Any alternative solution that how can I use an array in template literals?我如何在模板文字中使用数组的任何替代解决方案?

This is my use case I have a query这是我的用例我有一个查询

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
        }
      }    
    }

But it gets converted to [Object Object] .但它被转换为[Object Object] I know there are limitations so if you can please suggest a better solution?我知道有限制,所以如果你能提出更好的解决方案吗?

This is my where object这是我的 where 对象

const where = [{ name: 'endDate', op: 'is null' }];

如果我理解正确,那么您要寻找的是:

filterBy: ${JSON.stringify(where)}, 

I used this function我用过这个功能

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('},{')}}]`;
};

and changed the query to并将查询更改为

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
        }
      }    
    }

and it worked.它奏效了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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