尝试从下面的示例 JSON 读取description
属性时出现以下错误消息。
类型错误:无法读取未定义的属性"说明" 将 JSON 数据读取到打字稿时
import {Age} from "./sample"
var a:Age;
console.log(a.description);
样本.json:
{
"title":"Example Schema",
"type":"object",
"properties":{
"firstName":{
"type":"string"
},
"lastName":{
"type":"string"
},
"age":{
"description":"Age in years",
"type":"integer",
"minimum":0
},
"hairColor":{
"enum":[
"black",
"brown",
"blue"
],
"type":"string"
}
},
"additionalProperties":false,
"required":[
"firstName",
"lastName"
]
}
这是一个工作的 StackBlitz。
由于这是打字稿,因此技巧是将json
转换为所需的类型。由于sample.json
不仅仅是注释中列出的Age
接口,因此我们将创建一个名为 PersonSchema 的新接口。
interface PersonSchema {
title: string;
properties: {
age: Age;
};
}
现在我们可以导入json
数据。注意:import {Age} from "./sample"
不起作用,因为示例文件json
且无法导出类型。
import data from './sample.json';
将其转换为所需的类型:
const person = data as PersonSchema;
访问年龄:
const age = person.properties.age;