假设一个schema
对象验证一个data
对象.
有没有什么黑魔法可以让我们在schema
型守卫之后缩小data
型属性的范围?
片段胜过千言万语:
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?
}
我正在考虑将Schema
转换为一个具有自定义getter函数的类,该函数将依赖asserts
关键字来相应地键入data
属性.(1) 我不确定这是否可行,(2)可能有更好的方法.
知道吗?