簡體   English   中英

我可以使用數組變量來定義 typescript 嗎?

[英]Can I use array variable to define typescript?

假設我有一個常量變量

const STATUS = {
    ACTIVE: "ACTIVE",
    DELETED: "DELETED",
  }

我有一個 function 輸入是狀態

const handleStatus = (status) {
//do some thing
}

我想為status定義接口,只接受'ACTIVE'和'DELETED',所以我必須像下面這樣手動定義

type status = 'ACTIVE' | 'DELETED'
const handleStatus = (status : status) {
//do some thing
}

我可以做類似的事情嗎

type status = Object.values(STATUS)

謝謝!

編輯:我定義type status = (typeof STATUS)[keyof typeof STATUS]但是當我嘗試檢查狀態是否有效時

const validStatus = Object.values(STATUS)
if(!validStatus.includes(status)) {
  //do something
}

Typescript 拋出錯誤

Argument of type 'string' is not assignable to parameter of type ...

有 2 個選項供您選擇。 作為在這種情況下使用enum進行切換的評論中的建議,另一種方法是使用keyof關鍵字,因為仍然希望將字符串文字作為類型:

type Status = keyof typeof STATUS;

PS:如果您更喜歡將值作為類型而不是鍵,則需要進行更多調整:

const STATUS = {...} as const // mark it as constant

type Status = (typeof STATUS)[keyof typeof STATUS];

對新增請求的答復

看起來像是打字與其價值之間的誤解。 您不能將類型設置為值,這意味着您必須使用已定義的類型創建一個變量(不要將類型名稱定義為小寫status ),因此示例如下:

type Status = (typeof STATUS)[keyof typeof STATUS];

// this is the value which needs to create with your created type
const status: Status = 'ACTIVE';

// you can set this type as: `Status[]` or 
// you don't need to do so cause
// tsc can infer correct type as `Status[]`
const validStatus = Object.values(STATUS);

if(!validStatus.includes(status)) {
  // ...
}

暫無
暫無

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

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