Home > Blockchain >  TypeScript Argument of type 'IAccount' is not assignable to parameter of type 'never&
TypeScript Argument of type 'IAccount' is not assignable to parameter of type 'never&

Time:04-19

I am getting the above error when using the following types:

export interface IAccounts {
    "accounts": Array<IAccount>;
}

export interface IAccount {
  "username": string;
  "assets": Array<any>;
}

I am trying to initialize an account in my JSON file inside of a class constructor:

constructor(username: string) {
        super();
        this.username = username;
        if(!fs.existsSync('db.json')){
            let accountsObj = { "accounts": [] };
            let account: IAccount = {"username": username, "assets": []};
            accountsObj.accounts.push(account); // <-- here is where i am getting the error
            fs.writeFileSync('db.json', JSON.stringify(accountsObj), (err: any) => {
                if(err) {
                    console.log(err);
                }
                else {
                    console.log('************************************************************')
                    console.log(`*  Account successfully created. Welcome, ${this.username}!*`)
                    console.log('************************************************************')
                }
            })
            this.accountsObj = this.getAccountsObject();
            this.account = account;
        }
        else {
            this.accountsObj = this.getAccountsObject();
            this.account = this.getAccount(this.username);
        }
        
        
    }

I have tried to get this to work in multiple ways, I feel like I am missing something in the interface definitions.

CodePudding user response:

You need to specify the type of accountsObj. Otherwise Typescript will not know the correct type and will asign { accounts: never[] } based on the assigned object to it.

let accountsObj: IAccounts  = { "accounts": [] }

// or

let accountsObj = { "accounts": [] } as IAccounts
  • Related