错误:类型错误:将 json 数据读取到打字稿时,无法读取未定义的属性"说明"



尝试从下面的示例 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;

最新更新