So ultimately I need to do mongoose find in my use case but before that i need to create a dynamic query to filter data while fetching. I have created a testInterface which has two field first is the action and the second is the value, action has the name of fields present in my mongoose model.
interface testInterface {
action:
| "testValue1"
| "testValue2"
| "testValue3"
| "testValue4"
| "testValue5";
value: number;
}
I am receiving the mongoose model field value from the req params, i need to use this value as action value and do my search.
var testquery: testInterface = { action: req.params.choice, value: 1 };
but follwoing error is thrown -
Type 'string' is not assignable to type '"testValue1" | "testValue2" | "testValue3" | "testValue4" | "testValue5"'.ts(2322) userChoice.tsx(29, 3): The expected type comes from property 'action' which is declared here on type 'testInterface'
Please suggest how can i achieve the following use case.
CodePudding user response:
I think you need to manually convert your string value to the corresponding union type value:
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");
}
}