簡體   English   中英

Typescript 類型,鍵嚴格由字符串聯合類型組成

[英]Typescript type with keys strictly made of a string union type

我需要創建一個具有多個屬性的類型,其中每個屬性都有自己的類型(即不能保證所有屬性都具有相同的類型。我還需要確保所有屬性名稱都嚴格來自另一個字符串聯合類型。

這是我需要實現的示例

type Operations = "create:op" | "update:op" | "delete:op";

// Next three type defs only to demonstrate that all of them are different and 
// they don't have any common ancestor, etc.
type CreateOperationParams = {
    foo: string
}

type UpdateOperationParams = {
    bar: boolean
}

type DeleteOperationParams = {
    baz: number
}

// All properties in this type must be from Operations
// and every item from Operations must be present here
// as a property
type OperationParams = {
    "create:op"?: CreateOperationParams | false
    "update:op"?: UpdateOperationParams | false
    "delete:op"?: DeleteOperationParams | false
}

如果OperationsParams是完全手動編碼的,那么很容易犯這樣的錯誤

type OperationParams = {
    // Property name is not one of Operations, a dot is used instead of a colon.
    // This case must raise TS error. Another error should be that the correct
    // value "create:op" is not present in type properties 
    "create.op"?: CreateOperationParams | false   
    ...
}

以上是我實際擁有的簡化示例。 我在Operations類型中有大約 40 個不同的值,其中一些名稱有點長,帶有一些特殊字符,如冒號或點。 我顯然可以小心地將它們全部復制並粘貼到OperationsParams類型中,並為每個類型定義正確的類型,但是發生錯誤的可能性非常高,尤其是在Operations發生變化時。

有什么方法可以實現我的場景,但強制OperationsParams的每個屬性都來自Operations聯合類型,並且不能添加其他屬性? 還要確保OperationsParams Operations

這是捕捉您意圖的類型:

type OpParam = CreateOperationParams | UpdateOperationParams | DeleteOperationParams;
type OperationParams = Partial<Record<Operations, OpParam | false>>

我在您的示例中添加了false 這是完整的代碼 - 操場

我們在這里做的是:

  • 我們說我們需要一個帶有Operations類型鍵的記錄
  • 我們說值可以是可能的 Param 類型之一(我把它放到 OpParam 中)
  • 我們用 Partial 包裝它以使屬性可選

這可能符合您的標准嗎?

type CreateParams = {
  "create:op"?: {
    foo: string
  }
}

type UpdateParams = {
  "update:op"?: {
    bar: boolean
  }
}

type DeleteParams = {
  "delete:op"?: {
    baz: number
  }
}

type OperationParams = CreateParams & UpdateParams & DeleteParams;

type Operations = keyof OperationParams;

const goodParams: OperationParams = {
  "create:op": {
    foo: "hey"
  },
  "delete:op": {
    baz: 3
  },
  "update:op": {
    bar: true
  }
}

const brokenParams: OperationParams = {
  //shows a compiler error as requested
  "create.op": {
    foo: "hey"
  },
  "delete:op": {
    baz: 3
  },
  "update:op": {
    bar: true
  }
}

暫無
暫無

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

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