虽然您的问题没有说明这一点,但我假设您希望以某种自动方式将编译时检查转换为运行时检查。考虑到这一点,我找到了these notes,我将用作此答案的基础。
从您的示例开始并修饰Textstyle 可能是什么,我们创建xyz.ts:
interface Textstyle {
bold: boolean;
font: string;
}
export interface xyz {
something?: string;
somethingStyle?: Textstyle;
}
然后为我们的示例安装其余的依赖项(下面是一个 shell 会话):
$ echo '{"private":true}' >package.json
$ npm install --save-dev typescript @tsconfig/recommended ts-json-schema-generator
$ echo '{"extends":"@tsconfig/recommended/tsconfig.json"}' >tsconfig.json
$ npx ts-json-schema-generator --path 'xyz.ts' >xyz_schema.json
如果我们在xyz_schema.json 中查看ts-json-schema-generator 的输出,我们会发现:
{
"$ref": "#/definitions/xyz",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"xyz": {
"additionalProperties": false,
"properties": {
"something": {
"type": "string"
},
"somethingStyle": {
"additionalProperties": false,
"properties": {
"bold": {
"type": "boolean"
},
"font": {
"type": "string"
}
},
"required": [
"bold",
"font"
],
"type": "object"
}
},
"type": "object"
}
}
}
由于 JSON 模式是一种已定义的格式,我们可以使用许多工具来验证我们的对象。这是我和Ajv一起整理的:
const Ajv = require("ajv");
const schema = require("./xyz_schema.json");
const ajv = new Ajv();
const validate = ajv.compile(schema);
const x1 = {
something: "hello world",
somethingStyle: {
bold: true,
font: "comic sans",
},
};
const x2 = {
wibbles: "wobble",
};
const testCases = [x1, x2];
testCases.forEach((x, i) => {
const valid = validate(x);
if (valid) {
console.log(`test case ${i} is valid`);
} else {
console.error(`test case ${i} is invalid`);
console.error(validate.errors);
}
});
哪些输出:
test case 0 is valid
test case 1 is invalid
[
{
instancePath: '',
schemaPath: '#/definitions/xyz/additionalProperties',
keyword: 'additionalProperties',
params: { additionalProperty: 'wibbles' },
message: 'must NOT have additional properties'
}
]