Say a schema object validates a data object.
Is there any kind of dark magic that would allow us to narrow down the type of a data property after a schema-based type guard?
Snippets are worth a thousand words:
function validate(data: Data, schema: Schema) {}
interface Data {
[key: string]: number | string | undefined;
}
interface Schema {
properties: {
[key: string]: { type: "number" | "string" } | undefined;
};
}
// Just for demo purposes: we don't know its exact shape until run time.
const schema: Schema = {
properties: {
firstName: {
type: "string",
},
},
};
// Idem.
const data: Data = {
firstName: "John",
};
validate(data, schema); // What kind of magic could happen here...
if (schema.properties.firstName?.type === "string") {
const firstName: string = data.firstName; // ...so that there's no error here?
}
I'm thinking about turning Schema into a class with a custom getter function that would rely on the asserts keyword to type the data property accordingly. (1) I'm not sure it's feasible and (2) there may be a better way.
Any idea?