首页 > 解决方案 > 类型“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": []
    }
  ]
}

标签: typescript

解决方案


您的问题是您定义了错误的接口。根据您的数据,您的界面应该是:

// 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


推荐阅读