首页  >  问答  >  正文

Typescript 中未分配的对象不能被错误检查

我正在尝试将以下 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。

P粉986860950P粉986860950185 天前410

全部回复(2)我来回复

  • P粉904450959

    P粉9044509592024-04-02 09:49:17

    解决在赋值之前无法使用变量的问题的解决方案非常简单 - 只需为其赋值即可。

    您可以明确其值最初是未定义,这就是已声明但未赋值的变量所发生的情况。或者您可以使用更有意的“无值”初始值,例如 null

    当然,这会将您的变量类型更改为包含此初始值的联合,但这与您使用它的方式一致,因此我认为这不会成为问题。

    顺便说一句,object 并不是一个很好用的类型。如果您有 linting,您可能会收到警告。某种形式的记录 对您来说更有用/更清晰?

    回复
    0
  • P粉752290033

    P粉7522900332024-04-02 09:29:28

    当你这样做时 ->

    let account: object;
    
    if (account) { // error here

    你告诉 Typescript 该帐户只能是一个对象,但是 Typescript 会让你延迟分配它,但是如果它检测到有可能永远不会将对象分配给帐户,它会给你 -> 变量“account”在分配之前使用。

    被视为您在进行真实测试 -> if (account) {

    逻辑上您的类型是objectundefined

    let account: object | undefined;
    
    if (account) { // No error

    在某些情况下,明确未设置的值可能更有意义,因此有些人也喜欢为此使用 null -> let account:object |空=空

    回复
    0
  • 取消回复