Below is a fixture file with optional properties that I have type guarded:
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) {
// Validation logic here
}
return true;
}
Instead of multiple if statements, any suggestions to improve the code?