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);
};
}
CodePudding user response:
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
Easy, but not recommended fix
Set strict
value to false
on your tsconfig
file
Another easy, but better way
Explicitly specify the error
type to any
try {
const accounts = await web3.eth.getAccounts();
callback(null, accounts[0]);
} catch (error: any) {
callback(error, null);
}
Best way
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
}
}