When handling data in my Typescript backend provided through an HTML form, I perform validations using type guards before writing to the database.
let myObject = { property: parseProperty(property) }
The expected type for "property" is defined as:
interface PropertyType = {
Field1: string;
Field2: string;
}
The property object undergoes validation with the following type guard:
const parseProperty = (property: unknown): PropertyType => {
if (!property || !isPropertyEntry(property)) {
throw new Error("Incorrect or missing property entry")
}
return property;
A yet incomplete typeguard below is used to validate the fields of the property's objects.
const isPropertyEntry = (property : unknown): property is PropertyType => {
if( !('Field1' in property) || !('Field2' in property) ) {
throw new Error("Incorrect or missing field/s in property");
}
...
...
}
TypeScript flags an error for the statements 'Field1' in property and 'Field2' in property:
Object is of type 'unknown'.ts(2571)
I am seeking guidance on how to properly validate the 'property' object and ensure that Field1 & Field2 exist and are of correct type.