type guards for optional parameters

I have the following fixture file that i have type guarded below. it has few optional properties

fixture file-

 {
      "profiles": [
        {
          "name": "Laakea",
          "phoneNumber": "2033719225",
          "authGroupName": "Drivers"
        },
        {
          "name": "Lkhagvasuren",
          "phoneNumber": "2033719225",
          "authGroupName": "Drivers"
        },
        {
          "name": "Joaquin",
          "phoneNumber": "2033719225"
        }
      ]
    }

type interface-

 export interface Profile {
      name: string;
      authGroupName?: string;
      phoneNumber?: string;
      email?: string;
    }

type guard function-

export function isValidProfiles(profiles: unknown): profiles is Profile[] {
  if (!Array.isArray(profiles)) {
    return false;
  }
  for (let index = 0; index < profiles.length; index += 1) {
    if (typeof profiles[index].name !== 'string') {
      return false;
    }
    if (profiles[index].email) {
      if (typeof profiles[index].email !== 'string') {
        return false;
      }
    }
    if (profiles[index].phoneNumber) {
      if (typeof profiles[index].phoneNumber !== 'string') {
        return false;
      }
    }
    if (profiles[index].authGroupName) {
      if (typeof profiles[index].authGroupName !== 'string') {
        return false;
      }
    }
  }

  return true;
}

i was wondering if i could write it better instead of all these if statements ?



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation