0

How to cast string to array of objects in Type Script?

I have following code working perfectly:

let nodes = new DataSet<any>([
      {id: 1, label: 'Node 1'},
      {id: 2, label: 'Node 2'},
      {id: 3, label: 'Node 3'},
      {id: 4, label: 'Node 4'},
      {id: 5, label: 'Node 5'}
    ]);

But when I try to use

let nodes2 = new DataSet<any>(this.someEntity.nodesConfig);

I get following error:

TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'any[]'.   Type >'undefined' is not assignable to type 'any[]'.

Here is SomeEntity:

export interface SomeEntity{
  id?: string;
  nodesConfig?: string;
  edgesConfig?: string;
}
tillias
  • 1,035
  • 2
  • 12
  • 30
  • possibly similar to: https://stackoverflow.com/questions/1086404/string-to-object-in-js – Peter S May 01 '20 at 20:52
  • Try please let nodes2 = new DataSet(this.someEntity.nodesConfig.split(””)); And you must check this.someEntity.nodesConfig before call DataSet – Oro May 01 '20 at 21:18
  • @PeterS JSON.parse() is a correct answer – tillias May 01 '20 at 21:27

0 Answers0