0

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>

1 Answers1

0

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();

demo

ksav
  • 20,015
  • 6
  • 46
  • 66
  • I defined the key type as ```number```. secondly, my code is also working if I simply ```console.log(department[1])``` – Saghar Francis Feb 09 '22 at 12:39
  • The problem is occuring when I am putting type in map argument like ```department: Department``` and then return a list – Saghar Francis Feb 09 '22 at 12:40
  • Because you are putting the incorrect type. – ksav Feb 09 '22 at 12:42
  • see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries – ksav Feb 09 '22 at 12:43
  • Object keys are always a string https://stackoverflow.com/questions/3633362/is-there-any-way-to-use-a-numeric-type-as-an-object-key – ksav Feb 09 '22 at 12:44