I am getting the above error when using the following types:
JavaScript
x
10
10
1
export interface IAccounts {
2
"accounts": Array<IAccount>;
3
}
4
5
export interface IAccount {
6
"username": string;
7
"assets": Array<any>;
8
}
9
10
I am trying to initialize an account in my JSON file inside of a class constructor:
JavaScript
1
28
28
1
constructor(username: string) {
2
super();
3
this.username = username;
4
if(!fs.existsSync('db.json')){
5
let accountsObj = { "accounts": [] };
6
let account: IAccount = {"username": username, "assets": []};
7
accountsObj.accounts.push(account); // <-- here is where i am getting the error
8
fs.writeFileSync('db.json', JSON.stringify(accountsObj), (err: any) => {
9
if(err) {
10
console.log(err);
11
}
12
else {
13
console.log('************************************************************')
14
console.log(`* Account successfully created. Welcome, ${this.username}!*`)
15
console.log('************************************************************')
16
}
17
})
18
this.accountsObj = this.getAccountsObject();
19
this.account = account;
20
}
21
else {
22
this.accountsObj = this.getAccountsObject();
23
this.account = this.getAccount(this.username);
24
}
25
26
27
}
28
I have tried to get this to work in multiple ways, I feel like I am missing something in the interface definitions.
Advertisement
Answer
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.
JavaScript
1
6
1
let accountsObj: IAccounts = { "accounts": [] }
2
3
// or
4
5
let accountsObj = { "accounts": [] } as IAccounts
6