所以最終我需要在我的用例中做 mongoose find 但在此之前我需要創建一個動態查詢來在獲取時過濾資料。我創建了一個 testInterface,它有兩個欄位,第一個是操作,第二個是值,操作具有我的貓鼬模型中存在的欄位的名稱。
interface testInterface {
action:
| "testValue1"
| "testValue2"
| "testValue3"
| "testValue4"
| "testValue5";
value: number;
}
我正在從 req 引數接收 mongoose 模型欄位值,我需要將此值用作操作值并進行搜索。
var testquery: testInterface = { action: req.params.choice, value: 1 };
但拋出以下錯誤 -
型別 'string' 不能分配給型別 '"testValue1" | "testValue2" | "testValue3" | "testValue4" | "testValue5"'.ts(2322) userChoice.tsx(29, 3): 預期的型別來自屬性 'action',它在型別 'testInterface' 上宣告
請建議我如何實作以下用例。
uj5u.com熱心網友回復:
我認為您需要手動將字串值轉換為相應的聯合型別值:
interface testInterface {
action:
| "testValue1"
| "testValue2"
| "testValue3"
| "testValue4"
| "testValue5";
value: number;
}
var testquery: testInterface = { action: convert(req.params.choice), value: 1 };
function convert(strVal: string) : testInterface["action"] {
switch (strVal) {
case "testValue1":
return "testValue1";
case "testValue2":
return "testValue2";
case "testValue3":
return "testValue3";
case "testValue4":
return "testValue4";
case "testValue5":
return "testValue5";
default:
throw new Error("Unsupported type");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365118.html
