我正在尝试将以下 js 转换为打字稿,但在检查我的 account 对象时遇到问题,因为它未分配,因此代码无法构建:
const accounts = state.msalInstance.getAllAccounts();
let account;
if (accounts.length) {
account = accounts[0];
} else {
await state.msalInstance
.handleRedirectPromise()
.then(redirectResponse => {
if (redirectResponse !== null) {
account = redirectResponse.account;
} else {
state.msalInstance.loginRedirect();
}
})
.catch(error) => {
console.error(`Error during authentication: ${error}`);
});
}
if (account) {}
上面的代码在js中工作正常,所以我已将其转换为以下ts,但现在最终的if将无法编译,因为我试图在分配任何内容之前使用帐户变量:
const accounts = state.msalInstance.getAllAccounts();
let account: object;
if (accounts.length) {
account = accounts[0];
} else {
await state.msalInstance
.handleRedirectPromise()
.then((redirectResponse: {
account: object;
}) => {
if (redirectResponse !== null) {
account = redirectResponse.account;
} else {
state.msalInstance.loginRedirect();
}
})
.catch((error: {
name: string;
}) => {
console.error(`Error during authentication: ${error}`);
});
}
if (account) {
// this won't compile anymore as account isn't assigned
}
如何更改 account 对象以便查看它是否为空或未定义?我尝试将其专门设置为 null,但它说我无法将对象设置为 null。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
当你这样做时 ->
let account: object; if (account) { // error here你告诉 Typescript 该帐户只能是一个
对象,但是 Typescript 会让你延迟分配它,但是如果它检测到有可能永远不会将对象分配给帐户,它会给你 ->变量“account”在分配之前使用。被视为您在进行真实测试 ->
if (account) {逻辑上您的类型是
object或undefinedlet account: object | undefined; if (account) { // No error在某些情况下,明确未设置的值可能更有意义,因此有些人也喜欢为此使用
null->let account:object |空=空