I am writing a User Defined Type Guard for my Angular project.
The following if statements (marked by my comments) work perfectly well — but i can't help but think there would be a more readable way to write them.
The following first checks that the Object passed to the function has the required props (and exits early if not).
The next (and third) if statement checks the value of the prop activity is a String.
The second and fourth if statements need to check that the values of props createdAt and updatedAt are either of the type String, or that they are Objects and that they have their own props .sv who's values is the String timestamp.
import { GridMetadata } from './grid-metadata';
export function isGridMetadata(obj: any): obj is GridMetadata {
[ 'activity', 'createdAt', 'totalReps', 'updatedAt' ].every((prop) => {
if (obj.hasOwnProperty(prop) === false) return false;
});
if (typeof obj.activity !== 'string') return false;
// TODO: Better way to write this?
if (typeof obj.createdAt === 'string') {}
else if (obj.createdAt.hasOwnProperty('.sv') && obj.createdAt['.sv'] === 'timestamp') {}
else return false;
if (typeof obj.totalReps !== 'number') return false;
// TODO: Better way to write this?
if (typeof obj.updatedAt === 'string') {}
else if (obj.updatedAt.hasOwnProperty('.sv') && obj.updatedAt['.sv'] === 'timestamp') {}
else return false;
return true;
}
There may indeed be a better an more readable way to write the entire function?!
Aucun commentaire:
Enregistrer un commentaire