Home > front end >  Property 'username' does not exist on type 'DATABASE_USERS'
Property 'username' does not exist on type 'DATABASE_USERS'

Time:11-02

error TS2339: Property 'username' does not exist on type 'DATABASE_USERS'.

This is the minimal code to reproduce the error. The code i posted before was not throwing the error.

I don't know why i can't access the property when it's clearly there if i print the object. I guess i'm missing something in the interface?

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": []
    }
  ]
}

CodePudding user response:

The problem in your case is you have wrong interfaces defined. Based on your data, your interfaces should be:

// 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[];
}

And with this tiny change, your program is fixed. Check this out at TS Playground: https://tsplay.dev/WJ8zDN

  • Related