I am processing some data in my backend (written in Typescript) provided via a form in html. Before writing the data to the database, I perform validations using type guards.
let myObject = { property: parseProperty(property) }
where the type definition for "property" is given as:
interface PropertyType = {
Field1: string;
Field2: string;
}
The property object is first parsed via the following type-guard:
const parseProperty = (property: unknown): PropertyType => {
if (!property || !isPropertyEntry(property)) {
throw new Error("Incorrect or missing property entry")
}
return property;
Then we use the typeguard below (which is incomplete) to validate property's objects fields.
const isPropertyEntry = (property : unknown): property is PropertyType => {
if( !('Field1' in property) || !('Field2' in property) ) { // <--- invalid statement
throw new Error("Incorrect or missing field/s in property");
}
...
...
}
TS throws an error for these two statements: 'Field1' in property & 'Field2' in property:
Object is of type 'unknown'.ts(2571)
My question is how would I do a proper validation of the object 'property' and make sure Field1 & Field2 exist and are correct type?
PropertyTypeinterface instead ofunknown, or supply it via a generic type argument (e.g.function isPropertyEntry<T>(property: T) ...