To ensure the input aligns with the expected interface, it is important to convert each property to the correct type.
function convertInputToParams(input:any) : Params {
var obj = typeof input === "string"
? JSON.parse(input)
: input;
obj.count = +obj.count;
obj.result = obj.result === "true" ? true : false;
return obj as Params;
}
An alternative approach would be to create a default instance of Params
with predefined properties, then iterate over them to verify that each property in the converted object matches the expected type.
function convertInputToInterface(example:any, input:any) {
Object.keys(example).forEach(function(key,index) {
if (!input[key]) return;
let exampleType = typeof example[key];
let inputType = typeof input[key];
if (exampleType !== inputType) {
if (exampleType == "string") input[key] = input[key] + "";
if (exampleType == "number") input[key] = +input[key];
if (exampleType == "boolean") input[key] = input[key] === "true" ? true : false;
// Handle other cases as needed
}
});
return input;
}