0

I am working with stenciljs using typescript, my component can be used anywhere and user can send data in stringified array or normal array for example as below

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

and user can also pass normal array well like below:

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

so in My stencil component i have below stuff.

       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[]'
            }
          }

}

I have provided error in comments, please refer above code, if I make @State:parsedData:any=[]; this works but I would like not to use any here, any help ?

htmldev
  • 63
  • 1
  • 9

1 Answers1

0

Use TypeScript Union Types

@State() parsedData: string | [] = [];
snsakib
  • 1,062
  • 9
  • 14
  • but this says :Property 'map' does not exist on type 'string | []'.Property 'map' does not exist on type 'string'. in render functio – htmldev Sep 30 '20 at 11:38
  • any help here, like I always want to map array elements – htmldev Sep 30 '20 at 13:27
  • You cann't use `map` on string. [Try this solution instead](https://stackoverflow.com/a/54092488/9611676) – snsakib Sep 30 '20 at 23:52