簡體   English   中英

動態表名 Prisma Typescript 錯誤

[英]Dynamic table names Prisma Typescript error

使用動態表名和 Prisma 時遇到 Typescript lint 錯誤。 我有以下代碼:

type Mode =  'category' | 'ingredients';
let mode: Mode;    
mode = req.query.mode as Mode;


if(mode === 'category'){
    const table = 'category';
    const lookup = 'categoriesOnDishes';
    const lookupItemIdKey = 'categoryId';
}else if(mode === 'ingredients'){
    const table = 'ingredient';
    const lookup = 'ingredientsOnDishes';
    const lookupItemIdKey = 'ingredientId';
}

let lookupData = await prisma?.[lookup].findMany({
                where : {
                        dishId : did
                    } 
    })

錯誤是:

在此處輸入圖像描述

元素隱式具有“任何”類型,因為“任何”類型的表達式不能用於索引類型“PrismaClient<PrismaClientOptions, never, RejectOnNotFound | 拒絕操作 | 未定義>'

如何解決這個問題。

提前致謝。

如果你 hover over lookup ,它會顯示一個額外的錯誤Cannot find name 'lookup' 原因是tablelookuplookupItemIdKey是塊范圍的常量,在外部 scope 中是不可見的。

您可以聲明三個單獨的條件常量( const table = mode === 'category'? 'table': 'ingredient'等),但您也可以使用解構在一個 go 中聲明所有三個:

const {table, lookup, lookupItemIdKey} = mode === 'category' ? {
  table: 'category',
  lookup: 'categoriesOnDishes',
  lookupItemIdKey: 'categoryId',
} : {
  table: 'ingredient',
  lookup: 'ingredientsOnDishes',
  lookupItemIdKey: 'ingredientId',
}

如果有兩種以上的模式,並且您不想嵌套條件表達式,您也可以使用 object:

const modeConstants: Record<Mode, Record<'table' | 'lookup' | 'lookupItemIdKey', string>> = {
  category: {
    table: 'category',
    lookup: 'categoriesOnDishes',
    lookupItemIdKey: 'categoryId',
  }, 
  ingredients: {
    table: 'ingredient',
    lookup: 'ingredientsOnDishes',
    lookupItemIdKey: 'ingredientId',
  }
}

const {table, lookup, lookupItemIdKey} = modeConstants[mode]

暫無
暫無

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

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