【问题标题】:Accept both stringified and normal array接受字符串化和普通数组
【发布时间】:2020-09-30 11:04:31
【问题描述】:

我正在使用 typescript 使用 stenciljs,我的组件可以在任何地方使用,并且用户可以在字符串化数组或普通数组中发送数据,例如如下

<my-component data ="JSON.stringify([1,3,4]") />

用户也可以像下面这样传递普通数组:

  <my-component data=[1,4,5] />

所以在我的模板组件中,我有以下内容。

       export class Charts {
          @Prop() data: string;
          @Prop() chartTitle: string;
          @State() parsedData= [];
        
          componentWillLoad() {
            try {
              this.parsedData = JSON.parse(this.data);
            } catch (error) {
              this.parsedData = this.data || [];  // here it gives me error Type 'string | undefined[]' is not assignable to type 'any[]'.
      Type 'string' is not assignable to type 'any[]'
            }
          }

}

我在 cmets 中提供了错误,请参考上面的代码,如果我使 @State:parsedData:any=[]; 有效,但我不想在这里使用任何东西,有什么帮助吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用TypeScript Union Types

    @State() parsedData: string | [] = [];
    

    【讨论】:

    • 但这说:属性'map'不存在于类型'string | []'.“字符串”类型上不存在属性“地图”。在渲染函数中
    • 这里有任何帮助,比如我总是想映射数组元素
    • 你不能在字符串上使用mapTry this solution instead
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2021-12-17
    • 2013-08-23
    相关资源
    最近更新 更多