'IAccount' 类型的 TypeScript 参数不可分配给 'never' 类型的参数
TypeScript Argument of type 'IAccount' is not assignable to parameter of type 'never'
我在使用以下类型时遇到上述错误:
export interface IAccounts {
"accounts": Array<IAccount>;
}
export interface IAccount {
"username": string;
"assets": Array<any>;
}
我正在尝试在我的 JSON 文件中的 class 构造函数中初始化一个帐户:
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);
}
}
我尝试以多种方式让它工作,我觉得我在接口定义中遗漏了一些东西。
您需要指定 accountsObj
的类型。否则 Typescript 将不知道正确的类型,并将根据分配给它的对象分配 { accounts: never[] }
。
let accountsObj: IAccounts = { "accounts": [] }
// or
let accountsObj = { "accounts": [] } as IAccounts
我在使用以下类型时遇到上述错误:
export interface IAccounts {
"accounts": Array<IAccount>;
}
export interface IAccount {
"username": string;
"assets": Array<any>;
}
我正在尝试在我的 JSON 文件中的 class 构造函数中初始化一个帐户:
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);
}
}
我尝试以多种方式让它工作,我觉得我在接口定义中遗漏了一些东西。
您需要指定 accountsObj
的类型。否则 Typescript 将不知道正确的类型,并将根据分配给它的对象分配 { accounts: never[] }
。
let accountsObj: IAccounts = { "accounts": [] }
// or
let accountsObj = { "accounts": [] } as IAccounts