Typescript 中未分配的物件不能被錯誤檢查
P粉986860950
P粉986860950 2024-04-01 20:38:54
0
2
400

我正在嘗試將以下 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粉986860950
P粉986860950

全部回覆(2)
P粉904450959

解決在賦值之前無法使用變數的問題的解決方案非常簡單 - 只需為其賦值即可。

您可以明確其值最初是未定義,這就是已宣告但未賦值的變數所發生的情況。或者您可以使用更有意的“無值”初始值,例如 null

當然,這會將您的變數類型更改為包含此初始值的聯合,但這與您使用它的方式一致,因此我認為這不會成為問題。

順便說一句,object 並不是一個很好用的型別。如果您有 linting,您可能會收到警告。某種形式的記錄 a> 對您來說更有用/更清晰?

P粉752290033

當你這樣做時 ->

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 |空=空

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!