Reputation: 349
I am fairly new to typescript so I am getting an error which say Argument of type 'unknown' is not assignable to parameter of type 'Error | null' and i can't understand why am i getting that. How do I solve this?
export function subscribeToAccount(
web3: Web3,
callback: (error: Error | null, account: string | null) => any
) {
const id = setInterval(async () => {
try {
const accounts = await web3.eth.getAccounts();
callback(null, accounts[0]);
} catch (error) {
callback(error, null);
}
}, 1000);
return () => {
clearInterval(id);
};
}
Upvotes: 6
Views: 11964
Reputation: 6853
The error is caused by this line:
callback(error, null);
The type of error
from catch (error)
is unknown
, and you specified that callback
function accepts Error | null
as its first parameter, hence why the error.
Read more here
Set strict
value to false
on your tsconfig
file
Explicitly specify the error
type to any
try {
const accounts = await web3.eth.getAccounts();
callback(null, accounts[0]);
} catch (error: any) {
callback(error, null);
}
Do a type checking inside the catch
try {
const accounts = await web3.eth.getAccounts();
callback(null, accounts[0]);
} catch (error) {
if (error instanceof Error ) {
callback(error, null);
} else {
// handle
}
}
Upvotes: 9