首頁  >  問答  >  主體

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粉986860950184 天前405

全部回覆(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
  • 取消回覆