Home > OS >  TS) How to format an array to match the type/interface of an external component?
TS) How to format an array to match the type/interface of an external component?

Time:06-30

So I am using a treeview library in react which takes an array of a built-in type NodeModule[]. The array I give to the tree component is being used in another component in a different format (with different key names). I changed the data (see "thirdTreeData") as below so that its objects have the same key names as NodeModule[]. But I get an error:

Argument of type '{ id: number; parent: number | null; text: string; }[] | undefined' is not assignable to parameter of type 'NodeModel[] | (() => NodeModel[])'.

What NodeModule[] looks like:

export declare type NodeModel<T = unknown> = {
 id: number | string;
 parent: number | string;
 text: string;
 };

How I changed it to match with the type NodeModule[]. (I renamed parent_id to parent and name to text)

const thirdTreeData = secondTreeData?.map(tree => {
return { id: tree.id, parent: tree.parent_id,  text: tree.name };
 });

This is what I see when I hover thirdTreeData,

const thirdTreeData: {
id: number;
parent: number | null;
text: string;
 }[] | undefined

(*secondTreeData's type is - const secondTreeData: ITree[] | undefined )

How do I turn its type to NodeModule[] so that I can pass in thirdTreeData successfully into the tree component as below?

const [treeData, setTreeData] = useState<NodeModel[]>(thirdTreeData);

I get the error above.

What I've tried: I tried putting : NodeModule[] in front of thirdTreeData but this didn't work :(

 const thirdTreeData :NodeModule[] = secondTreeData?.map(tree => 

I'm new to typescript so thank you so much in advance

CodePudding user response:

okay i think i figured it out.. to satisfy the type of NodeModel[], I had to pass in '|| 0' for 'parent' so that it becomes a number when tree.parent_id is null. Also to make sure that thirdTreeData does not take 'undefined', I used a ternary to pass in an empty array when secondTreeData is undefined!

const thirdTreeData: NodeModel[] = secondTreeData
? secondTreeData.map(tree => {
  return { id: tree.id, parent: tree.parent_id || 0,  text: tree.name };
  })
: [];

CodePudding user response:

The error message says that the thirdTreeData doesn't satisfy the NodeModel type, so you can simply fix that by saying that parent property should be number or null and id a number in NodeModel type as the following code snippet::

 export declare type NodeModel<T = unknown> = {
     id: number; // <-- id should be a number
     parent: number | null; // <-- parent number or null
     text: string;
 };

The treeData state generic should be NodeModel[] or undefined though:

const [treeData, setTreeData] = useState<NodeModel[] | undefined>(thirdTreeData);

Hope that works.

  • Related