When creating data validation APIs, I have a common approach where I include two functions - one that returns a boolean value and another that throws an error. The throwing function typically has a void return type.
interface MyType {
numberField: number;
stringField: string;
}
function isMyType(o: any): o is MyType {
return typeof o === "object"
&& o !== null
&& typeof o.numberField === "number"
&& typeof o.stringField === "string";
}
function validateMyType(o: any): void {
if (!isMyType(o)) {
throw new Error("Invalid MyType object.")
}
}
I am interested in using a type predicate so that any subsequent code within the same block or sub-block can infer the type of the object automatically.
const input: any = ...;
validateMyType(input);
// At this point, I want TypeScript to recognize that input conforms to MyType
Is there a way to achieve this?