如何处理 return 类型 Maybe<unknown>
How to handle a return type Maybe<unknown>
我正在使用打字稿,我正在尝试从当前用户那里获取帐户,就像它在 metamask 官方文档中显示的那样 Metamask Doc:
const accounts = await window.ethereum.request({
method: "eth_accounts",
});
对 request
函数的调用 return 是 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
函数的 return 并使打字稿接受它作为字符串数组。
谢谢。
错误表明请求的返回值可能为空、未定义甚至 not-an-array 值。所以你必须在访问它的值之前检查这些情况。
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.
}
我正在使用打字稿,我正在尝试从当前用户那里获取帐户,就像它在 metamask 官方文档中显示的那样 Metamask Doc:
const accounts = await window.ethereum.request({
method: "eth_accounts",
});
对 request
函数的调用 return 是 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
函数的 return 并使打字稿接受它作为字符串数组。
谢谢。
错误表明请求的返回值可能为空、未定义甚至 not-an-array 值。所以你必须在访问它的值之前检查这些情况。
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.
}