typescript - 类型“DATABASE_USERS”上不存在属性“用户名”
问题描述
错误 TS2339:类型“DATABASE_USERS”上不存在属性“用户名”。
这是重现错误的最少代码。我之前发布的代码没有抛出错误。
如果我打印对象,我不知道为什么当它明显存在时我无法访问该属性。我想我在界面中遗漏了一些东西?
import * as fs from "fs";
interface DATABASE_USERS {
[index: number]: {
username: string,
key?: string
}
}
interface DATABASE {
users?: DATABASE_USERS[]
}
const loadFile = (filename: string): string | null => {
let retValue: string | null;
try {
retValue = fs.readFileSync(filename, { encoding: "utf-8" })
} catch(e) {
retValue = null;
}
return retValue;
};
const getUsersFromDB = (jsonPath: string): null | DATABASE => {
const data: string | null = loadFile(jsonPath);
let jsonData: DATABASE = {} as any;
if (data) {
try {
jsonData = JSON.parse(data);
} catch(error) {
return null
}
} else {
return null;
}
if (!data) {
return null;
}
return jsonData;
}
const database = getUsersFromDB("./pm.json");
if (database?.users?.length) {
console.log("USERS:");
for (let i = 0; i < database?.users.length; ++i) {
console.log(` ${i + 1} - ${database?.users[i]?.username}`);
}
}
pm.json
{
"users": [
{
"username": "Jhon",
"services": []
},
{
"username": "Kevin",
"key": "abc",
"services": []
}
]
}
解决方案
您的问题是您定义了错误的接口。根据您的数据,您的界面应该是:
// interfaces and classes are written in CamelCase with first capital letter
// all caps is commonly used for constants
interface User {
username: string;
key?: string;
services?: string[];
}
interface Database {
users?: User[];
}
有了这个微小的改变,你的程序就固定了。在 TS Playground 中查看:https ://tsplay.dev/WJ8zDN
推荐阅读
- c++ - 如何避免具有相同类型参数的函数中的错误
- sql - Access SQL SELECT 查询:需要在 WHERE 子句中使用表别名?
- jsf - 打开新选项卡时使用受 JSF 保护的视图时出错
- javascript - 无法将 JSON 数据嵌入(&理解)到 Treemap
- python - 具有嵌套结果的 Python 正则表达式
- mysql - MySQL alter table 给出未知列错误
- c++ - 如何禁用 Openscenegraph 几何节点中的状态属性?
- bash - grep 多行中的特定字符串
- php - 使链接页面上的图像显示在图像源中
- c# - 按钮已禁用 - DialogHost 和日历