Issue
I am learning react with typescript. I have one dictionary of the department in which employees data of department is stored in the form of an array.
type Department = {
Emp_Id: number,
Name: string,
Age: number
}
let dict: {[DepartmentNo: number]: Department[] } = {};
dict[0] = [ {Emp_Id: 1, Name:"Test", Age: 23},
{Emp_Id: 2, Name:"Test", Age: 23},
{Emp_Id: 3, Name:"Test", Age: 23}
];
dict[1] = [ {Emp_Id: 1, Name:"Test 2", Age: 23},
{Emp_Id: 2, Name:"Test 3", Age: 23},
{Emp_Id: 3, Name:"Test 4", Age: 23}
];
dict[2] = [ {Emp_Id: 1, Name:"Test 2", Age: 23},
{Emp_Id: 2, Name:"Test 3", Age: 23}
];
I created a function that will return me an unordered list.
const printDepartment = () => {
// getting error in map argument: department
Object.entries(dict).map((department: Department) => {
let count = 0;
// here also saying condition will always return true
if(dict[count] != 2){
return (<ul>
<li>{department.Emp_Id}</li>
<li>{department.Name}</li>
</ul>)
}
})
}
in my return I am simply calling this function:
<div>
{
printDepartment()
}
</div>
Solution
The type of keys on your dict
will always be string
. If you change that, the types in the Array.map
element will be correctly inferred as [string, Department[]]
.
type Department = {
Emp_Id: number;
Name: string;
Age: number;
};
let dict: { [DepartmentNo: string]: Department[] } = {};
dict[0] = [
{ Emp_Id: 1, Name: "Test", Age: 23 },
{ Emp_Id: 2, Name: "Test", Age: 23 },
{ Emp_Id: 3, Name: "Test", Age: 23 },
];
dict[1] = [
{ Emp_Id: 1, Name: "Test 2", Age: 23 },
{ Emp_Id: 2, Name: "Test 3", Age: 23 },
{ Emp_Id: 3, Name: "Test 4", Age: 23 },
];
dict[2] = [
{ Emp_Id: 1, Name: "Test 2", Age: 23 },
{ Emp_Id: 2, Name: "Test 3", Age: 23 },
];
const printDepartment = () => {
Object.entries(dict).map((entry) => { // [string, Department[]]
console.log({ key: entry[0], value: entry[1] });
});
};
printDepartment();
Answered By - ksav
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.