簡體   English   中英

為什么 typescript 枚舉在嚴格模式下被視為可能未定義? 怎么修?

[英]Why typescript enum is seen as possibly undefined in strict mode? How to fix?

我收到來自 Typescript ( 4.8.2 ) STRICT的錯誤:

Argument of type 'State | undefined' is not assignable to parameter of type 'State'.
  Type 'undefined' is not assignable to type 'State'. ts(2345)

使用此代碼:

enum State {
  Completed = "COMPLETED",
  Discontinued = "DISCONTINUED",
}

type Player = {
  description: Scalars["String"];
  state: State;
  team?: Maybe<Team>;
};

let player: Partial<Player>;

const isOK = [State.Completed, State.Discontinued].includes(player.state);

我該如何解決?

是因為Partial<Player>嗎?

是的, Partial<Player>可能沒有定義的state ,TypeScript 對 arrays 的includes()方法的類型要求搜索的項目可以分配給數組元素類型。 (請參閱為什么 Array.prototype.includes(searchElement) 的參數需要與數組元素相同的類型?

處理這個問題的最簡單方法是在使用includes()之前通過明確檢查它來消除undefined的可能性:

const isOK = (player.state !== undefined) &&
    [State.Completed, State.Discontinued].includes(player.state);

Playground 代碼鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM