Search code examples
typescripttypescript-typingstypescript2.0typescript1.8

how to define a type under forEach in typescript?


I have an array of PersonTypes objects and would like to only use partial of key inside a forEach loop. what is more precise, correct coding in typescript to provide a type? I can do something like people.forEach((person: Pick<PersonTypes, 'name' | 'gender'> or people.forEach((person: PersonTypes) =>{ or people.forEach((person: any) =>{ what is right way to code in typescript

export type PersonTypes = {
  name: string;
  value: string;
  gender: boolean;
};
const people: PersonTypes[] = [
  {name: 'apl', value: 'apple', gender: true},
  {name: 'gal', value: 'google', gender: false},
]
people.forEach((person: Pick<PersonTypes, 'name' | 'gender'>) =>{
//people.forEach((person: PersonTypes) =>{
//people.forEach((person: any) =>{
  console.log(person.name);
  console.log(person.gender);
} )

Solution

  • You should just stick to:

    people.forEach((person: PersonTypes) =>{
    
    
    });
    

    This is because each object within the people array is of type PersonTypes, and there is no actual need to extract properties away from the type.

    In fact, there is no need to explicitly type person as PersonTypes, as people is of PersonTypes[]. TypeScript will automatically infer that each object within the array is PersonTypes, so this would be sufficient:

    people.forEach((person) =>{
    
    
    });  
    

    Alternatively, you may choose to destructure the parameter, which will make your function more concise and clean.

    people.forEach(({ name, gender }) =>{  
      console.log(name);
      console.log(gender);
    });