O zod é muito útil mesmo, ainda mais lidando com types grandes e complexos.
Também é possível fazer validações simples criando type guards usando type predicates e typeof
:
type MyData = {
name: string;
age: number;
};
// https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
function isMyDataType(data: any): data is MyData {
if (typeof data?.name !== "string") return false;
if (typeof data?.age !== "number") return false;
return true;
}
const json1 = '{ "name": "John", "age": 30 }';
const data1 = JSON.parse(json1);
if (isMyDataType(data1)) {
console.log("`data1` is valid:", data1);
} else {
console.log("`data1` is not valid");
}
const json2 = '{ "firstName": "John", "yearOfBirth": 1994 }';
const data2 = JSON.parse(json2);
if (isMyDataType(data2)) {
console.log("`data2` is valid:", data2);
} else {
console.log("`data2` is not valid");
}
// output:
// `data1` is valid: { name: 'John', age: 30 }
// `data2` is not valid
Depois de checar o type, sabe-se que é o type certo dentro do if
:



Ou, por exemplo, fora do if
com throw
:

Também é possível incorporar o zod no type guard, algo como:
function isComplexDataType(data: any): data is MyComplexData {
const result = complexSchema.safeParse(data);
return result.success;
}