Iam使用类型记录和iam试图从当前用户那里获取帐户,就像在元问询正式文档Metamask医生上显示的那样
const accounts = await window.ethereum.request({
method: "eth_accounts",
}); 对request函数的调用以Maybe<unknown>类型返回结果。
然后,我试图访问这样的第一个帐户元素,因为它应该是一个字符串数组:
accounts[0]但我有以下错误:
Object is possibly 'null' or 'undefined'.ts(2533)
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Partial<unknown>'.
Property '0' does not exist on type 'Partial<unknown>'.ts(7053)那么,我该如何处理这种情况呢?我需要正确地获得request函数的返回,并使类型记录接受为字符串数组。
谢谢。
发布于 2022-01-28 07:11:31
这些错误表明,从请求返回的值可能为null、未定义或甚至不是一个数组值。所以你必须先检查这些情况,然后才能得到它的价值。
const accounts = await window.ethereum.request({
method: "eth_accounts",
});
if (accounts && Array.isArray(accounts)) {
// Here you can access accounts[0]
} else {
// Handle errors here if accounts is not valid.
}https://stackoverflow.com/questions/70888720
复制相似问题