簡體   English   中英

從數據庫加載可區分聯合

[英]Loading discriminated unions from a database

我有一個像這樣定義的歧視工會:

enum ShapeKind {
  Square = 'sqaure',
  Rectangle = 'rectangle',
}

interface Square {
    kind: ShapeKind.Square;
    size: number;
}

interface Rectangle {
    kind: ShapeKind.Rectangle;
    width: number;
    height: number;
}

type Shape = Square | Rectangle;

我希望能夠從數據庫中加載它們。 我有一個具有以下簽名的方法:

getShape(kind: ShapeKind, id: string): Shape

這將執行如下數據庫查詢,並根據記錄的kind字段返回與接口匹配的對象:

SELECT * FROM shapes WHERE id = ? AND kind = ? LIMIT 1

如果我傳入ShapeKind.Rectangle我知道它必須返回一個Rectangle (或拋出未找到的錯誤),但目前無論我傳入什么,返回類型始終為Shape

如何讓編譯器理解這個規則?

您可以使用函數重載

function getShape(kind: ShapeKind.Rectangle, id: string): Rectangle
function getShape(kind: ShapeKind.Square, id: string): Square
function getShape(kind: ShapeKind, id: string): Shape {
  // Your query here  
  switch (kind) {
    case ShapeKind.Rectangle:
      return {
        kind: ShapeKind.Rectangle,
        width: 1,
        height: 1,
      }
    case ShapeKind.Square:
      return {
        kind: ShapeKind.Square,
        size: 1,
      }
  }
}

暫無
暫無

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

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